开发者

Can someone explain this Java syntax to me?

Can someone explain this Java syntax to me? What are those brackets doing inside the outer parentheses?

addWindowListener(new WindowAdapter() {
        pub开发者_运维百科lic 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. 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.


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.


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). Java programmers will often prefer the anonymous class approach if the anonymous class does not get too big/complicated/important.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜