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
open class BClass(val x: Int){
open val y = 20
}interface IInterface {
fun canIDoSomething()
}val bClassObj : BClass = object : BClass(10), IInterface {
override val y: Int = 30 override fun canIDoSomething() {
println("bClassObj : can I do something")
}}
Now, will go step by step. First the equivalent class.
public class BClass {
private int x;
private int y = 20;
public BClass(int xValue){
this.x = xValue;
}
public void someFunction(){
System.out.println("SomeClass : some Function");
}
}
Please ignore getter and setters. Now the interface,
public interface IInterface {
void canIDoSomething();
}
Now to create an object of BClass along with overriding the function we can write the below code,
BClass bClassObj = new BClass(10){
@Override
public void someFunction() {
//super.someFunction();
System.out.println("bClassObj : can I do something");
}
};
Or let’s say we have some other function which takes BClass object as the parameter.
public void iCanDoSomething(BClass bClassObj){
System.out.println("Hey, I am doing something with
BClass object");
}iCanDoSomething(new BClass(20){
@Override
public void someFunction() {
//super.someFunction();
System.out.println("Overridden someFunction
from BClass");
}
});
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
//BClasspublic class BClass {
private int x;
private int y = 20;
public BClass(int xValue){
this.x = xValue;
}
public void someFunction(){
System.out.println("SomeClass : some Function");
}
}// IInterfacepublic interface IInterface {
void canIDoSomething();
}//IntermediateClass extending BClass and IInterfacepublic class IntermediateClass extends BClass implements IInterface {
public IntermediateClass(int xValue) {
super(xValue);
}
@Override
public void canIDoSomething() {
}
}
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 :)