简体   繁体   中英

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() {
        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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM