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 sta
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
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.
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.
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