Reputation: 2472
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"?
Upvotes: 0
Views: 401
Reputation: 86381
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.
Upvotes: 2
Reputation: 608
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.
Upvotes: 0