问题
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