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

后端 未结 14 1283
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:47

    I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:

    public void someMethod()
    {
        new Thread(new Runnable() {
            public void run()
            {
                // do stuff
            }
        }).start();
    }
    

    In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:

    public void someMethod()
    {
        new Thread(new MyRunnable()).start();
    }
    
    // ... several methods down ... //
    
    class MyRunnable implements Runnable
    {
        public void run()
        {
            // do stuff
        }
    }
    

    That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.

    I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.

提交回复
热议问题