Reputation: 45
I have the impression that it is possible to instantiate an interface:
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
This prints "test"
. Why? The class doesn't implement the interface.
Also it creates an instance of it using new TestA()
but I read interfaces cannot be instantiated.
Can someone please explain why it prints successfully ?
Upvotes: 0
Views: 90
Reputation: 10536
What you are doing here is creating an anonymous class, and instantiating it. So your object's type is not TestA
, but actually the type of the anonymous class.
TestA myObject = new TestA(){ ... }
is a shortcut for :
class ClassA implements TestA { ... }
TestA myObject = new ClassA();
In this example, although the type of the reference myObject is TestA
, the type of the referenced object is ClassA
, which implements TestA
.
You can read about anonymous classes in the Java Tutorial here.
The last step of "what is going on", is your call of System.out.println
on the created object, which as a consequence calls its toString()
method.
So to break up all the steps that are happening, your code is equivalent to :
public class Test {
public static void main(String[] args){
class ClassA implements TestA {
public String toString(){
return "test";
}
}
TestA myObject = new ClassA();
String myString = myObject.toString();
System.out.println(myString);
}
}
So to answer your precise questions :
Test
doesn't implement the interface, the anonymous class does. It does both because it is declared as implementing it, and because it correctly implements the abstract method toString
If you would like to check that second point, you can try removing the body of your anonymous class definition. It won't compile :
System.out.println(new TestA()); // Compile error
Upvotes: 6