views:

81

answers:

3
 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?

+2  A: 

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

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

Stefan Kendall
A: 

The answer is "A" - "test" is displayed in the console.

duffymo
While correct, this answer lacks heart. (I'm not the downvoter though.)
jjnguy
"heart"? Please describe
duffymo
@duffy. Well you gave a technically correct answer. But, the answer feels mechanical and thoughtless. An answer with 'heart' will attempt to answer the question behind the question...if you know what I mean.
jjnguy
Time doesn't always permit "heart". One does what one can.
duffymo
+7  A: 

What you are seeing here is an anonymous inner class:

Given the follwoing interface:

interface Inter{
    public String getString();
}

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

Inter instance = new Inter() {  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.

jjnguy