问题
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 ?
回答1:
What is going on
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);
}
}
Answer to your precise questions
So to answer your precise questions :
- indeed, your class
Testdoesn'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 methodtoString - indeed, interfaces cannot be instantiated. In this case, you are not instantiating the interface, but the anonymous class that you define as implementing the interface.
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
来源:https://stackoverflow.com/questions/39181406/ability-to-instantiate-an-interface