Abhinav
Abhinav

Reputation: 8168

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.setVisible(true);
        f.setSize(300,300);
        f.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
}

Upvotes: 0

Views: 302

Answers (5)

ANSHUL CHAUHAN
ANSHUL CHAUHAN

Reputation: 1

No, you can't create the Object of Abstract Class directly, But you can use an anonymous inner class to do that and you also can implement your own methods inside the anonymous class. Please refer - http://www.easybix.com/can-create-object-abstract-class/

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49372

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.

Upvotes: 3

Adam Arold
Adam Arold

Reputation: 30538

You are subclassing the WindowAdapter class and you provide an implementation and instantiate it at the same time. This is what basically happens here.

This is called an anonymous inner class.

As others suggested here the java tutorials are containing excellent explanations about this.

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

It creates an implementation of WindowAdapter at Runtime and the implementation consists of the code you have provided. It's called anonymous, because it doesn't have a name, therefore you cannot refer it by name. When it's executed once, it cannot be executed again.

Upvotes: 0

sadhu
sadhu

Reputation: 1479

Its no more abstract as you have implemented the abstract method with System.exit(0)

Upvotes: 1

Related Questions