Can we create an object of an interface?

shirsendu shome picture shirsendu shome · Oct 22, 2010 · Viewed 44.6k times · Source
interface TestA {
    String toString();
}

public class Test {
    public static void main(String[] args) {
        System.out.println(new TestA() {
            public String toString() {
                return "test";
            }
        });
    }
}

What is the result?

A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.

What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?

Answer

jjnguy picture jjnguy · Oct 22, 2010

What you are seeing here is an anonymous inner class:

Given the following interface:

interface Inter {
    public String getString();
}

You can create something like an instance of it like so:

Inter instance = new Inter() {
    @Override
    public String getString() {
        return "HI";
    }
};

Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.