I'm fairly new to programming but I've taken the Intro CS class at my school, so I understand most of the basics (or thought I did). I'm trying to teach myself some OpenGL via JOGL and I came across a few lines of code that I couldn't understand. Am I missing something?
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
I checked the Javadoc, and WindowAdapter
is an abstract class. So how can he be instantiating it?
Or is this even creating an instance?
It almost looks like the code extends WindowAdapter
or overrides the windowClosing
method, but how is that possible without writing a new class?
It almost looks like the code extends
WindowAdapter
or overrides thewindowClosing
method
This is exactly what's happening.
but how is that possible without writing a new class?
In fact, the code is creating a new (anonymous) class. It's just that the syntax is different to what you've come across so far. Take a look at the tutorial.
For a discussion of how anonymous classes are used, see How are Anonymous (inner) classes used in Java?
The Concept used is Anonymous class !! .... Since WindowAdapter is an abstract class you cannot make it's object it but using Anonymous Class concept you can call its constructor or use the functions without assigning it to an object of it's type ..
Another way of using Abstract classes data variables and methods is to make objects of it's derived classes
In this way u can have a WindowAdpater instance passed in the parameter without any error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With