When to use inner classes in Java for helper classes

后端 未结 11 2133
醉梦人生
醉梦人生 2020-12-04 07:24

If I have for example a class along with a helper class to do some of its functionality, does it make sense to make it as an inner class.

    public class F         


        
11条回答
  •  臣服心动
    2020-12-04 07:45

    Inner classes make sense when they are tiny and don't need names. Listeners in GUIs are classic examples where they make sense.

    If the class is big and important, it should be named and placed in a separate file.

    The listener classes in normal GUI examples do one tiny thing, usually just dispatch to some other function to do real work.

    I also often use static nested classes (which are technically not inner classes) for classes which are only used in the context of another class - Map.Entry is a good example of this. It's only used in conjunction with a Map, so having the definition of Entry be a part of the Map interface makes organizational sense.

    I don't generally have much use for other types of nested classes, like nonstatic member classes and local classes. But they do occasionally come in useful. For a good example of a legitimate use for member classes, see the source code for LinkedList.ListItr. This is a private inner class whose purpose is to provide an implementation of ListIterator for a LinkedList. To do this, it's useful to have access to the private data inside the LinkedList. To achieve this using only top-level classes, it would have been necessary to expose more public methods in LinkedList to allow the ListIterator to get at the underlying implementation of the LinkedList. Instead, using an inner class allows LinkedList to keep its implementation private, as it should be.

提交回复
热议问题