Anonymous class with interface

后端 未结 4 1891
挽巷
挽巷 2021-01-16 14:24

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

相关标签:
4条回答
  • 2021-01-16 15:07

    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

    0 讨论(0)
  • 2021-01-16 15:16

    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.

    0 讨论(0)
  • 2021-01-16 15:21

    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.

    0 讨论(0)
  • 2021-01-16 15:23

    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

    0 讨论(0)
提交回复
热议问题