Can we create an interface object?

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?

but. test
B. null
C. An exception is thrown at run time.
D. Compilation error due to an error on line 1.
E. Compilation fails due to an error on line 4.
F. Compilation error due to an error on line 5.

What is the answer to this question and why? I have one more question on this. In line 4, we create object A. Is it possible to create an interface object?

+25
java interface anonymous-class
Oct 22 '10 at 19:01
source share
5 answers

What you see 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 this:

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

You now have an instance of the interface that you defined. But you should note that what you actually did is determined by the class, which implements the interface and instantiates the class at the same time.

+76
Oct 22 '10 at 19:05
source share

test should be an exit. This is an example of an anonymous inner class.

This is a very common pattern used with the Comparator interface as emulation of closures.

+5
Oct 22 '10 at 19:03
source share

The trick doesn't quite apply to the anonymous inner class, this print test calls the toString method override, and in System.out.println the object that it implicitly calls the toString method.

+1
Jan 03 '11 at 19:15
source share

Try this too ... Anonymous class name is created!

 Inter instance = new Inter() { public String getString(){ return "HI"+this.getClass(); } }; 
+1
Feb 15 '11 at 12:11
source share

I do not know the meaning of this question. If this is an interview question, I can say that everything is in order. But in real time, this is not the right approach to implement inheritance. So, to answer the question, here you are making an anonymous inner class .

Here you create a class and , implementing inheritance , write

 System.out.println(new TestA() { public String toString() { return "test"; } }); 

and of course the result will be test

-one
Mar 21 '14 at 12:19
source share