我们可以创建一个接口对象吗?
interface TestA {
String toString();
}
public class Test {
public static void main(String[] args) {
System.out.println(new TestA() {
public String toString() {
return "test";
}
});
}
}
结果如何?
A.测试
B. 空
C. 运行时抛出异常。
D. 由于第 1 行错误,编译失败。
E. 由于第 4 行错误,编译失败。
F. 由于第 5 行错误,编译失败。
这道题的答案是什么?为什么?关于这个问题我还有一个疑问。在第 4 行中,我们正在创建 A 的对象。是否可以创建接口的对象?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您在这里看到的是 匿名内部类:
给定以下接口:
您可以像这样创建类似其实例的内容:
现在,您拥有了您定义的接口的实例。但是,您应该注意,您实际上所做的是定义一个实现该接口的类,并同时实例化该类。
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.
test
应该是输出。这是匿名内部类的示例。这是一种非常常见的模式,与 Comparator 接口一起用作闭包的模拟。
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.技巧不仅仅在于匿名内部类,它打印测试是因为它重写了 toString 方法,而 System.out.println 则隐式调用了它的 toString 方法。
The trick is not only about the anonymous 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.也试试这个...匿名类的名称已生成!
Try this too... The name of anonymous class is generated!
我们可以创建匿名类的对象 ,实现接口:
如果您有一个接口,声明了一个方法
toString
,您可以首先创建一个实现此接口的类,然后创建此类的对象:或者您可以创建一个对象一个匿名类来简化此代码:
在这两种情况下都会打印
“test”
。We can create an object of an anonymous class, that implements the interface:
If you have an interface, that declares one method
toString
, you can first create a class, that implements this inerface, and then create an object of this class:Or you can create an object of an anonymous class to simplify this code:
In both cases it prints
"test"
.我不知道这个问题的意义。如果这是一个面试问题,那么我可以说没问题。但实际上,这并不是实现继承的正确方法。因此,回到问题的答案,这里您正在做的是一个匿名内部类。
这里你实例化一个类并通过编写实现继承,
当然结果将是
test
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