interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
结果是什么?
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.
这个问题的答案是什么?为什么?关于这个问题我还有一个疑问。在第 4 行中,我们正在创建 A 的对象。是否可以创建接口(interface)的对象?
最佳答案
您在这里看到的是 anonymous inner class :
给定以下界面:
interface Inter {
public String getString();
}
您可以像这样创建类似它的实例的东西:
Inter instance = new Inter() {
@Override
public String getString() {
return "HI";
}
};
现在,您拥有了定义的接口(interface)的实例。但是,您应该注意,您实际上所做的是定义一个实现该接口(interface)的类,并同时实例化该类。
关于java - 我们可以创建一个接口(interface)对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56593234/