Java Reference
In-Depth Information
13.2
Simple Uses of Inner Classes
The ruling ideas of each age have ever been the ideas of its ruling class.
KARL MARX and FRIEDRICH ENGELS,
The Communist Manifesto
Inner classes are classes defined within other classes. In this section, we will describe
one of the most useful applications of inner classes, namely, inner classes used as
helping classes.
Helping Classes
Defining an inner class is straightforward; simply include the definition of the inner
class within another class, as follows:
inner class
public class OuterClass
{
private class InnerClass
{
Declarations_of_InnerClass_Instance_Variables
Definitions_of_InnerClass_Methods
}
Declarations_of_OuterClass_Instance_Variables
Definitions_of_OuterClass_Methods
}
As this outline suggests, the class that includes the inner class is called an outer class .
The definition of the inner class (or classes) need not be the first item(s) of the outer
class, but it is good to place it either first or last so that it is easy to find. The inner class
need not be private, but that is the only case we will consider in this section. We will
consider other modifiers besides private in Section 13.3 .
An inner class definition is a member of the outer class in the same way that
the instance variables of the outer class and the methods of the outer class are
members of the outer class. Thus, an inner class definition is local to the outer class
definition. So you may reuse the name of the inner class for something else outside
the definition of the outer class. If the inner class is private, as ours will always be in
this section, then the inner class cannot be accessed by name outside the definition
of the outer class.
There are two big advantages to inner classes. First, because they are defined
within a class, they can be used to make the outer class self-contained or more
self-contained than it would otherwise be. The second advantage is that the inner
and outer classes' methods have access to each other's private methods and private
instance variables.
outer class
 
 
Search WWH ::




Custom Search