Creating an “object” of an interface

半城伤御伤魂 提交于 2019-12-20 06:13:43

问题


Today I had a bit of an argument with a friend who claimed that an interface object can be created. When I said that it's impossible, he showed me the following piece of code, which seemed similar to anonymous classes.Now the question is, what's the right answer?

public interface I {
    public void f();
}

public class InterfaceTest {
    public static void main(String []args){
        new I(){
            @Override
            public void f() {
                System.out.println("HELLO");                
            }           
        };
    }
}

Can this really be called creating an interface "object"?


回答1:


No, this is creating an instance of an anonymous class that implements the interface.

Here's the definitive answer from the Java Language Specification, section 15.9:

Both unqualified and qualified class instance creation expressions may optionally end with a class body. Such a class instance creation expression declares an anonymous class (§15.9.5) and creates an instance of it.




回答2:


No, it is (an instance of) an anonymous class.




回答3:


This is anonymous class creation. The class of the instance created above extends java.lang.Object and implements the interface I. So, technically, the above code creates an Object object.



来源:https://stackoverflow.com/questions/7586277/creating-an-object-of-an-interface

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