简体   繁体   English

匿名内部类中的接口如何工作?

[英]How does the interface in anonymous inner class work?

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? 据我所知,我们无法实例化一个接口,那么这是怎么发生的呢?

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. 您正在声明一个实现MyInter接口的匿名内部类。 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.. 你正在创建一个对象,一个匿名对象,但是MyInter作为超类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM