문제

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.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top