NestedObjectsImplyNestedClasses
DRAFT

Misconception:

If we have an object that “contains” other objects (e.g., a menu containing menu items), then their classes are nested, too (e.g., the menu class contains the menu item class).

Incorrect

If objects are part of a containment hierarchy, their classes are nested, too

Correct

Correction
Here is what's right.

Wrong! Having containment of objects does not mean that the classes (the types) of those objects are nested, too.

Nesting classes is all about hiding them. If you nest a class in another class, you move it out of view (even if it’s public, it still is kind of moved out of direct view, because it needs to be accessed via the outer class, e.g., Outer.Inner).

“Nesting” (containment, trees of) objects is not really about hiding the objects. You “nest” objects (you create “containment” hierarchies, or trees, of objects), when you have a container object (e.g., a folder) that contains a component object (e.g., a regular file). This does not mean that the component class is put inside the container class.

Usually the classes (the types) are not nested. In general, you very rarely have inner classes. The most common situation is when you have anonymous inner classes for listeners. Other situations are Iterator implementations inside collections. Or Runnable implementations. Otherwise, try to keep classes at the top level.

Language

Java

Concepts

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.