[英]Can someone explain this Java syntax to me?
Can someone explain this Java syntax to me? 有人可以向我解释这种Java语法吗? What are those brackets doing inside the outer parentheses?
括号内的括号在做什么?
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
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. 它创建一个扩展
WindowAdapter
的未命名类(也可以指定一个接口,在这种情况下,该类将实现该接口),并创建该类的一个实例。 Inside the brackets, you must implement all abstract methods or all interface methods, and you can override methods too. 在方括号内,您必须实现所有抽象方法或所有接口方法,并且您也可以覆盖方法。
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 .
这是一个潜在有用的SO问题 ,还有很多其他问题 。
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. 为了补充andersoj的答案,通常在方法需要X实例但X是抽象类或接口时使用它们。
Here, you're actually creating a derived class from WindowAdapter, and overriding one of the methods to do a specific task. 在这里,您实际上是从WindowAdapter创建派生类,并覆盖执行特定任务的方法之一。
This syntax is very common for event handlers / listeners. 对于事件处理程序/侦听器,此语法非常常见。
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:
您可以想象如果需要将其创建为顶级类,代码将是什么样子:
class CloseApplicationWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
Then, inside your code you would do: 然后,在您的代码内执行以下操作:
CloseApplicationWindowAdapter adapter = new CloseApplicationWindowAdapter();
addWindowListener(adapter);
Both solutions have exactly the same effect (althoug the anonymous class would create a Class$1.class
file, for instance). 两种解决方案都具有完全相同的效果(例如,匿名类将创建
Class$1.class
文件)。 Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important. 如果匿名类不会变得太大/太复杂/不重要,那么Java程序员通常会更喜欢匿名类方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.