|
|
|
|||
|
Implementing Nested ClassesAs you learned in Using an Inner Class to Implement an Adapter Java lets you define a class as a member of another class. Such a class is called a nested class and is illustrated here:
You use nested classes to reflect and enforce the relationship between two classes. You should define a class within another class when the nested class makes sense only in the context of its enclosing class or when it relies on the enclosing class for its function. For example, a text cursor makes sense only in the context of a particular text component. As a member of its enclosing class, a nested class has a special privilege: It has unlimited access to its enclosing class's members, even if they are declared private. However, this special privilege isn't really special at all. It is fully consistent with the meaning of private and the other access specifiers. The access specifiers restrict access to members for classes outside of the enclosing class. The nested class is inside of its enclosing class so that it has access to its enclosing class's members. Like other members, a nested class can be declared static (or not). A static nested class is called just that: a static nested class. A nonstatic nested class is called an inner class. These are illustrated in the following code:
As with static methods and variables (normally called class methods and
variables), a static nested class is associated with its enclosing
class. And like class methods, a static nested class cannot refer
directly to instance variables or methods defined in its enclosing
class-it can use them only through an object reference.
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods. Also, because an inner class is associated with an instance, it cannot define any static members itself. To help differentiate the terms nested class and inner class further, we suggest you think about them in the following way. The term "nested class" reflects the syntactic relationship between two classes; that is, syntactically, the code for one class appears within the code of another. In contrast, the term "inner class" reflects the relationship between instances of the two classes. Consider the following classes:
The interesting feature about the relationship between these two
classes is not that InnerClass is syntactically defined within
EnclosingClass.
Rather, it's that an instance of InnerClass can exist
only within an instance of EnclosingClass
and that it has direct access
to instance variables and methods of its enclosing instance.
The following diagram illustrates this idea.
![]()
Other Facts about Nested ClassesLike other classes, nested classes can be declared | |||
|