How does the interface in anonymous inner class work?

青春壹個敷衍的年華 提交于 2019-12-01 08:32:40

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.

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..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!