有人可以向我解释一下这个 Java 语法吗?
有人可以向我解释一下这个 Java 语法吗? 外括号内的括号有什么作用?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Can someone explain this Java syntax to me?
What are those brackets doing inside the outer parentheses?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它称为匿名内部类。它创建一个扩展 WindowAdapter 的未命名类(也可以指定一个接口,在这种情况下该类将实现该接口),并创建该类的一个实例。在括号内,您必须实现所有抽象方法或所有接口方法,并且也可以重写方法。
It's called an anonymous inner class. It creates an unnamed class that extends
WindowAdapter
(it would also have been possible to specify an interface, in which case the class would implement that interface), and creates one instance of that class. Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too.这是一个匿名内部类——括号表示类声明的开始和结束。这是一个潜在的有用的SO问题,以及其他一些。
This is an anonymous inner class -- the brackets denote the beginning and ending of the class declaration. This is a potentially useful SO question, and a bunch of others.
为了补充 andersoj 的答案,当方法需要 X 的实例,但 X 是抽象类或接口时,通常会使用它们。
在这里,您实际上是从 WindowAdapter 创建派生类,并重写其中一个方法来执行特定任务。
这种语法对于事件处理程序/侦听器来说非常常见。
And to complement andersoj's answer, you usually use them when a method expects an instance of X, but X is an abstract class or an interface.
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task.
This syntax is very common for event handlers / listeners.
它是一个匿名内部类。这只是一条捷径。您可以想象如果您需要将其创建为顶级类,代码会是什么样子:
然后,在您的代码中您将执行以下操作:
两种解决方案具有完全相同的效果(尽管匿名类将创建一个
Class$1例如,.class
文件)。如果匿名类不会变得太大/复杂/重要,Java 程序员通常会更喜欢匿名类方法。It is an anonymous inner class. It is just a shortcut. You can imagine how the code would look like if you needed to create it as a top level class:
Then, inside your code you would do:
Both solutions have exactly the same effect (althoug the anonymous class would create a
Class$1.class
file, for instance). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.