interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString(){
return "test";
}
});
}
}
在java中,你永远不能实例化java中的接口(interface)。但是为什么上面的代码打印“test”作为输出而不是引发错误?
最佳答案
因为您不是实例化接口(interface)
,而是定义(并同时实例化)一个新的类
,因此是一个新类型,它实现TestA
但它没有名字。
这是一个 anonymous class .
关于java - 在Java中,new TestA()和TestA obj = new TestA()有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053189/