aps
aps

Reputation: 2472

Creating an "object" of an interface

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

Answers (3)

Andy Thomas
Andy Thomas

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

Vladimir Ivanov
Vladimir Ivanov

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

michael667
michael667

Reputation: 3260

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

Upvotes: 2

Related Questions