简体   繁体   中英

What is this in java? Attaching methods “on the fly”?

I saw something like this today:

    frame.addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

What does the following part mean?

new AClass(){ this part }

Can I "extends" and create a new instance of this class inline?

I have tried to google it, but I didnt know how what it was called =/

PS: learning java =p

It's called an "anonymous class"... it's a shorthand way of implementing an interface, or extending an existing class (usually an abstract "Adapter" or "Helper" class), without bothering to name it.

You see it commonly in Swing code... implementing window and mouse listeners.

This looks (at face value) like a decent discussion of the topic: http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html

Cheers. Keith.

To add to Bohemian's answer, it's the same as doing something like this

class MyWindowAdapter extends WindowAdapter() {

        @Overide 
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
}

and

frame.addWindowListener(new MyWindowAdapter());

It is just an anonymous inner class, it is useful when you are only going to use that interface implementation only once, it can be very useful as otherwise you would have to create an entire class just for that.

It's called an anonymous class.

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