How are Anonymous inner classes used in Java?

后端 未结 18 1338
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:19

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

18条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:55

    Anonymous inner class is used in following scenario:

    1.)For Overriding(Sub classing) ,When class definition is not usable except current case:

    class A{
       public void methodA() {
          System.out.println("methodA");
        }
    }
    class B{
        A a = new A() {
         public void methodA() {
            System.out.println("anonymous methodA");
         }
       };
    }
    

    2.)For implementing an interface,When implemention of interface is required only for current case:

    interface interfaceA{
       public void methodA();
    }
    class B{
       interfaceA a = new interfaceA() {
         public void methodA() {
            System.out.println("anonymous methodA implementer");
         }
       };
    }
    

    3.)Argument Defined Anonymous inner class:

     interface Foo {
       void methodFoo();
     }
     class B{
      void do(Foo f) { }
    }
    
    class A{
       void methodA() {
         B b = new B();
         b.do(new Foo() {
           public void methodFoo() {
             System.out.println("methodFoo");
           } 
         });
       } 
     } 
    

提交回复
热议问题