Nested Types

The classes, interfaces, and enumerated types we have seen so far in this book have all been defined as top-level classes. This means that they are direct members of packages, defined independently of other types. However, type definitions can also be nested within other type definitions. These nested types, commonly known as " inner classes,” are a powerful and elegant feature of the Java language. A type can be nested within another type in four ways:

Static member types

A static member type is any type defined as a static member of another type. A static method is called a class method, so, by analogy, we could call this type of nested type a “class type,” but this terminology would obviously be confusing. A static member type behaves much like an ordinary top-level type, but its name is part of the namespace, rather than the package, of the containing type. Also, a static member type can access the static members of the class that contains it. Nested interfaces, enumerated types, and annotation types are implicitly static, whether or not the static keyword appears. Any type nested within an interface or annotation is also implicitly static. Static member types may be defined within top-level types or nested to any depth within other static member types. A static member type may not be defined within any other kind of nested type, however.

Nonstatic member classes

A "nonstatic member type” is simply a member type that is not declared static. Since interfaces, ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.