这似乎是从接口创建一个对象;它是如何运作的?
interface Int {
public void show();
}
Int t1 = new Int() {
public void show() {
System.out.println("message");
}
to.show();
interface Int {
public void show();
}
Int t1 = new Int() {
public void show() {
System.out.println("message");
}
to.show();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在定义一个实现
Int
接口的匿名类,并立即创建一个thatAnonymousClassYouJustMade
类型的对象。You're defining an anonymous class that implements the interface
Int
, and immediately creating an object of typethatAnonymousClassYouJustMade
.此表示法是
So in the end 你将创建一个具体类的实例,其行为是你内联定义的。
您也可以通过抽象类来实现这一点,方法是为所有内联抽象方法提供实现。
This notation is shorthand for
So in the end you're creating an instance of a concrete class, whose behavior you defined inline.
You can do this with abstract classes too, by providing implementations for all the abstract methods inline.
这种匿名内部类的特殊语法的作用是创建一个名为
Test$1
的类。您可以在 Test 类旁边的类文件夹中找到该类文件,如果您打印了t1.getClass().getName()
您也可以看到该文件。What this special syntax for anonymous inner classes does under the hood is create a class called
Test$1
. You can find that class file in your class folder next to the Test class, and if you printedt1.getClass().getName()
you could also see that.我认为你的对象与界面无关。如果您注释掉整个界面,您仍然会得到相同的输出。它只是创建的匿名类。我认为,除非您使用类“实现”,否则您无法实现该接口。但我不知道在你的情况下如何不会发生命名冲突。
i think your object has nothing to do with the interface. If you comment out the whole interface, still you will get the same output. Its just anonymous class created. I think, unless you use the class "implements" you cant implement the interface. But i dunno how naming collision doesn't happen in your case.