Is usage of anonymous classes in Java considered bad style or good?

后端 未结 14 1279
Happy的楠姐
Happy的楠姐 2020-12-05 01:58

I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.

But what doe

14条回答
  •  情话喂你
    2020-12-05 02:52

    Anonymous class is mostly seen in GUI application specially for events handling.Anonymous class is useful in cases of implementing small interfaces that contains one or two methods..For example.. you have a class where you have two or three threads and you want to perform two or three different tasks using those threads.In this situation you can take the help of anonymous class to perform your desired tasks. look at the follow example

    class AnonymousClass{
    
    public static void main(String args[]){
    
    
        Runnable run1=new Runnable(){
    
            public void run(){
    
                System.out.println("from run1");
            }
    
        };
        Runnable run2=new Runnable(){
    
            public void run(){
    
                System.out.println("from run2");
            }
    
        };
        Runnable run3=new Runnable(){
    
            public void run(){
    
                System.out.println("from run3");
            }
    
        };
    
    
    
        Thread t1=new Thread(run1);
        Thread t2=new Thread(run2);
        Thread t3=new Thread(run3);
    
    
        t1.run();t2.run();t3.run();
    
    }
    }
    

    output:

    from run1

    from run2

    from run3

    In the above snap of code i have used three threads to perform three different tasks. Look i have created three anonymous classes that contains the implementation of the run method to perform three different small tasks.

提交回复
热议问题