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

后端 未结 15 2303
鱼传尺愫
鱼传尺愫 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:19

    Inner classes are appropriate when trying to emulate multiple inheritance. It is similar to what happens under the hood with C++: when you have multiple inheritance in C++, the object layout in memory is actually a concatenation of several object instances; the compiler then works out how the "this" pointer shall be adjusted when a method is invoked. In Java, there is no multiple inheritance, but an inner class can be used to provide a "view" of a given instance under another type.

    Most of the time, it is possible to stick to single inheritance, but occasionally multiple inheritance would be the right tool to use, and this is the time to use an inner class.

    This means that inner classes are somehow more complex than usual classes, in the same way that multiple inheritance is more complex than single inheritance: many programmers have some trouble wrapping their mind around that concept. Hence the "best practice": avoid inner classes because it confuses your coworkers. In my view, this is not a good argument, and at my workplace we are quite happy to use inner classes when we deem it appropriate.

    (A minor drawback of inner classes is that they add one extra level of indentation in the source code. This is a bit irksome at times, when one wants to keep the code within 79 columns.)

    0 讨论(0)
  • 2020-12-01 07:24

    Inner classes are often used to "pass a behavior" as a parameter of a method. This capability is supported in an elegant way by other languages with closures. Using inner classes produces some not elegant code (IMHO) because of a language limitation but it's useful and widely used to handle events and blocks in general with inner classes.

    So I would say that inner classes are very useful.

    0 讨论(0)
  • 2020-12-01 07:27

    Cleanliness. It's easier to comprehend code if it's broken into logical pieces, not all mushed into the same file.

    That said, I do not consider the judicious use of inner classes to be inappropriate. Sometimes these inner classes only exist for one purpose, so I would then have no problem with their being in the only file in which they are used. However, this does not happen that much in my experience.

    0 讨论(0)
提交回复
热议问题