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?
The trick is not exactly about the annonymous inner class, this prints test cause it overrides the toString method and while System.out.println a Object it implicit call it's toString method.
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.Try this too... The name of annonymous class is generated!
I don't know the significance of this question. If this is an interview question, then I can say it's okay. But in real time it's not the right approach to implement an inheritance.So coming to the answer of the question, here what you are doing is an anonymous inner class .
Here you are instantiating a class and implementing the inheritance by writing,
and ofcourse the result would be
test
What you are seeing here is an anonymous inner class:
Given the following interface:
You can create something like an instance of it like so:
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.