问题
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?
回答1:
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.
回答2:
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.
回答3:
yes, keep in mind that YOU CAN NOT instantiate an abstract class or interface..
this is wrong:
MyInter mi = new MyInter();
but you must have read that a super class reference variable can hold the reference to the sub class object.
so by creating
MyInter mi=new MyInter(){
public void display() {
System.out.println("this is anonymous class1");
}
};
you are creating an object , an anonymous object , that however has MyInter as the superclass..
来源:https://stackoverflow.com/questions/19287364/how-does-the-interface-in-anonymous-inner-class-work