3

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

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
lucaswxp
  • 2,031
  • 5
  • 23
  • 34
  • Try stariting from here: http://www.cs.sjsu.edu/faculty/beeson/courses/cs160/LectureNotes/12-EventDrivenProgramming.html – Emre Yazici Jul 02 '11 at 22:59

4 Answers4

3

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.

corlettk
  • 13,288
  • 7
  • 38
  • 52
2

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());
Bala R
  • 107,317
  • 23
  • 199
  • 210
2

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.

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
1

It's called an anonymous class.

Bohemian
  • 412,405
  • 93
  • 575
  • 722