What are the purposes of inner classes

前端 未结 10 1841
终归单人心
终归单人心 2020-11-29 23:14

I am reviewing the concept of inner classes in java. so far from what I\'ve understood and applied java inner classes has a link or access to the methods and fields of its o

10条回答
  •  渐次进展
    2020-11-29 23:22

    As a general rule, objects should be designed for a single responsibility (Highly cohesive). In other words, any object designed well, should perform a single coherent task. This would be considered best practice for object orientated design.

    Sometimes, however, a developer may design a class that requires a separate specialized class in order to work. This separate specialized class could be considered a helper class.

    If the helper class is not used by any other class, then it would be considered a prime candidate as an inner class

    As elicited by ncmathsadist above, an example of inner class use would be in the implementation of Event handlers.

    For example, in designing a graphical user interface (GUI), a developer may have created a button that performs a particular task after the user presses it.

    The button would need an event handler which listens for when that particular button is pressed.

    In this case, creating the event handler for the button as an inner class would be best practice as the inner class would not be utilized anywhere else other than with the specific button within the GUI class.

提交回复
热议问题