Java (anonymous or not) inner classes: is it good to use them?

后端 未结 15 2328
鱼传尺愫
鱼传尺愫 2020-12-01 06:48

In some of my projects and in some books was said to not use inner class (anonymous or not, static or not) - except in some restricted conditions, like

15条回答
  •  一个人的身影
    2020-12-01 07:12

    Anonymous inner classes are often used when we need to implement interface with one method, like Runnable, ActionListener and some other.

    One more great appliance of anonymous inner classes is when you don't want to make a subclass of some class but you need to override one (or two) of its methods.

    Named inner classes can be used when you want achieve tight coherence between two classes. They aren't so useful as anonymous inner classes and I can't be sure that it's a good practice to use them ever.

    Java also has nested (or inner static) classes. They can be used when you want to provide some special access and standard public or default access levels aren't enough.

提交回复
热议问题