harish
harish

Reputation: 328

Can we create object to interfaces and abstract classes?

f.addMouseMotionListener(new MouseAdapter() {
    public void mouseDragged(MouseEvent e) 
    {
        String s="Mouse dragging :X = "+e.getX()+" Y= "+e.getY();
        tf.setText(s);
    }
    });

i read that we cannot instantiate objects for Abstract classes...but here we are creating new MouseAdapter() ..can someone explain how is it done with these anonymous classes..thank u.

Upvotes: 1

Views: 1459

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477710

You're not creating an instance of MouseAdapter, you are creating an instance of an anonymous class inheriting from MouseAdapter.

More verbosely, this could have been written:

class Goo extends MouseAdapter { public void mouseDragged(){...} };

f.addMouseMotionListener(new Goo());

Upvotes: 3

Ivan
Ivan

Reputation: 776

You don't see it doesn't mean it won't happen. Just from the code, you use new MouseAdapter() to construct an object. However, if you try to read the content in .class file, you will find that the inner class has name, the usual case is,

class MouseAdapter$1 extends MouseAdapter

Till this, you should clear about everything. :)

Upvotes: 0

Related Questions