bismeet marwaha Thank you for your response.

Ideally, the same thing is not possible in Java because we can’t create an anonymous object of a class, along with implementing an interface also.

To give a workaround we need another intermediate Class extending BClass and implementing the interface after which we can create the anonymous object.

Let me show you the code for that. First the Kotlin code

Now, will go step by step. First the equivalent class.

Please ignore getter and setters. Now the interface,

Now to create an object of BClass along with overriding the function we can write the below code,

Or let’s say we have some other function which takes BClass object as the parameter.

In Kotlin we can even go one step further. If we want to create these objects of BClass but at the same time, we need to implement interface also. This is not possible directly in Java. To achieve this in Java we need to create a separate class which extends our class (BClass) and implements interface. Later we can create an anonymous object of the same class similar to the above example. Whereas in Kotlin we don’t need to create that class.

The final Java equivalent code for the above Kotlin code is

And now you can create the object of IntermediateClass.

Hope it helps. The reason I used the same classes names is that it will make you better understand. Let me know if this helps you.

Happy Coding :)



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store