Some inner classes are exposed publicly (eg Map.Entry
in Java) but that is by far the exception rather than the norm.
Inner classes are, basically, an implementation detail.
For example, Swing makes extensive use of inner classes for event listeners. Without them you would end up polluting the global namespace with a bunch of classes you otherwise don't need to see (which may make their purpose harder to determine).
Essentially inner classes are a form of scope. Package access hides classes from outside the package. Private inner classes hide that class from outside that class.
Inner classes in Java are also a substitute for a lack of function pointers or method delegates (which are in C#) or closures. They are the means of passing a function to another function. For example, in the Executor
class you have:
void execute(Runnable r);
so you can pass a method in. In C/C++ that could be achieved with:
void execute(void (*run)());
being a pointer to a function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…