interface MyInter {
public void display();
}
class OuterClass8 {
public static void main(String arg[]) {
MyInter mi=new MyInter() {
public void display() {
System.out.println("this is anonymous class1");
}
};
mi.display();
}
}
As far as I know, we cannot instantiate an interface, so how did this happen?
You cannot instantiate an interface, but you can provide a reference of an interface to an object of the class implementing the interface, so in code you are implementing interface and creating an object of that class and give reference of that class.
By declaring
MyInter mi=new MyInter(){
public void display() {
System.out.println("this is anonymous class1");
}
};
You are declaring an anonymous inner class that implements the MyInter interface. It's similar to doing
public class MyInterImpl implements MyInter {
public void display() {
System.out.println("this is anonymous class1");
}
}
and creating an instance
MyInterImpl mi = new MyInterImpl();
but you are doing it anonymously.
You are correct in thinking that you cannot instantiate an interface. You cannot do
MyInter mi = new MyInter();
but you can do what is presented above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With