|
||
Lesson 7
Objective
|
Inner classes
Discuss how inner classes are declared and used. |
|
|
Inner classes
The release of JDK 1.1 introduced support for inner classes (and inner
interfaces), which are classes (or interfaces) that are declared as a member of another class or interface.
The following is an example of an inner class definition:
class Outer {
// Outer class body
class Inner {
// Inner class body
}
}
The Inner class (referred to as Outer.Inner) is defined
within the context of the Outer class (referred to as simply Outer). Since inner classes are class members, they
are allowed to have access modifiers (public, protected, private, or package access). They may
also be declared as abstract, final, or static.
Access modifier: A modifier that is used to limit access to a class, class member, or constructor.
Inner classes are also referred to as nested classes .
Nested class : A class that is declared as a member of another class or interface. Non-static inner classes
An instance of a non-static inner class is associated with an enclosing scope.
Static inner classes
This enclosing scope is the instance of the outer class in which it is created. Variables and methods that are declared in the outer class are accessible within the inner class. Enclosing scope : The instance of an outer class in which an instance of an inner class is created.
static inner classes differ from non-static inner classes in that they do not have an object instance as an
enclosing scope. Instead, static inner classes have a static enclosing scope and are considered to be equivalent to
a top-level class (and are referred to as top-level classes ). Static inner classes may access static
variables that are defined in any enclosing classes.
Since static inner classes are not associated with an object instance, they may only have static members. Likewise, a non-static inner class may not have static members. Top-level class: A class that is not nested or a static inner class.
Multiple levels of inner classes are possible but are usually impractical.
|
||
|
|
||