This chapter covers all aspects of nested classes. In compiler terminology, nesting means “putting something inside another thing”. Everyone who has read this far will be comfortable with nesting methods and data fields inside classes. In this chapter we explain the different ways a class can be nested inside another class, and what it all means.
Nested classes are another in the (ever-lengthening) list of “Java features that were introduced to make one specific thing quicker to write”. There's a trade-off though. While nested classes make event-handlers simpler to write, they also add complexity to the compiler and to the features that programmers must learn.
Nested classes will make more sense when we have covered event-handlers for the GUI (Chapter 20), so you could skim the rest of this chapter until then. For now, just note that there are ways you can nest classes inside each other like Russian dolls, and postpone an in-depth reading until you need it.
The name “nested class” suggests you just write a class declaration inside a class, and you're done! Actually, there are four different kinds of nested classes specialized for different purposes, and given different names.
All classes are either:
Top-level or nested
Nested classes are:
Static classes or inner classes
Inner classes are:
Member classes or local classes or anonymous classes
Figure 12-1 represents the hierarchy and terminology of nested classes in a diagram.
A nested class is any class whose declaration occurs within the body of another class or interface. Up to now, we have been dealing exclusively with top-level classes. A top-level class is any class that is not nested.
You can declare nested classes as final, private, protected, or public, just like other members. Access protection protects against classes outside the enclosing class. It never affects the enclosing class or other classes inside it. They have full visibility into each other. A nested class declared as final
ensures that the nested class cannot be extended.
18.218.97.75