Abhinav Abhinav - 1 year ago 85
Java Question

Is the object of abstract class is created while using anonymous inner class?

Having a little trouble understanding Anonymous Inner classes

Here s the code that I have.I know that WindowAdapter class is an Abstract class, then what does the line "new WindowAdapter()" means? Are we creating an object of WindowAdapter class which is an abstract class.Confused!!!

Class Myframe extends Frame
public static void main(String args[])
Myframe f=new Myframe();
f.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)

Answer Source

It is creating an object of an anonymous class which extends WindowAdapter class without writing the code to subclass it.

From the Java Tutorials:

Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name.

This is a shortcut to create an object of a subclass without explicitly writing a separate class which extends WindowAdapter.The point is that you need the object from inside the code of a method so you never refer to them elsewhere, so you don't need to create a separate class for them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download