How are Anonymous inner classes used in Java?

后端 未结 18 1230
孤独总比滥情好
孤独总比滥情好 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 06:01

    The best way to optimize code. also, We can use for an overriding method of a class or interface.

    import java.util.Scanner;
    abstract class AnonymousInner {
        abstract void sum();
    }
    
    class AnonymousInnerMain {
        public static void main(String []k){
            Scanner sn = new Scanner(System.in);
            System.out.println("Enter two vlaues");
                int a= Integer.parseInt(sn.nextLine());
                int b= Integer.parseInt(sn.nextLine()); 
            AnonymousInner ac = new AnonymousInner(){
                void sum(){
                    int c= a+b;
                    System.out.println("Sum of two number is: "+c);
                }
            };
            ac.sum();
        }
    
    }
    

提交回复
热议问题