peter
peter

Reputation: 8473

Anonymous class with interface

I am confused about the concept of interface when dealing with anonymous inner class. As far as I know that you can't instantiate an interface in Java, so the following statement would have a compile error

     ActionListener action = new ActionListener();  // compile error

What happen when it deals with anonymous class? why does it allow to use new? For example:

     JButton button = new JButton("A");
     button.addActionListener(new ActionListener(){    //this is fine
           @Override
           public void actionPerformed(ActionEvent e){

           }
     };

Does the compiler just make a class and implement ActionListener behind the scene? How does it work?

Upvotes: 1

Views: 943

Answers (4)

Samuel
Samuel

Reputation: 17171

You're defining an inner class with a sequentially assigned name like 1, 2, 3 etc. At the same time you're instantiating the inner class with the new keyword. You don't care about the name of the inner class because you're using it anonymously. If you look in your bin directory you'll see a class file for each of the anonymous definitions. For example if you used an anonymous class in a class, Foo, you would have Foo.class and Foo$1.class created for you. I believe this means that you could instantiate more of the anonymous classes at a later date using reflection.

Upvotes: 1

saum22
saum22

Reputation: 882

You are creating a class and implementing the interface when working with anonymous class.you can override the methods or implement the method inside the anonymous class

    A a= new A(){ 

               }; 

Here a is a reference variable of type A which is referring not to A but to an object of class which implement A who doesn't have a name

Upvotes: 0

Renato Lochetti
Renato Lochetti

Reputation: 4568

When you create an inner-class, you are instantiating an anonymous class that implements the interface.

In your case, The effect is the same of: public class Foo implements ActionListener

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405745

It allows you to create a new anonymous class that implements ActionListener because you're providing the implementation, you're just not giving it a class name.

Upvotes: 5

Related Questions