Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code instantiating or extending an abstract class without creating a new class?

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?

like image 331
AdamJames Avatar asked Jul 09 '13 05:07

AdamJames


2 Answers

It almost looks like the code extends WindowAdapter or overrides the windowClosing 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?

like image 164
NPE Avatar answered Nov 07 '22 03:11

NPE


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.

like image 8
Vaido Avatar answered Nov 07 '22 05:11

Vaido