Java Reference
In-Depth Information
PITFALL: Other Uses of Inner Classes
In this section we have shown you how to use an inner class in only one way, namely to
create and use objects of the inner class from within the outer class method definitions.
There are other ways to use inner classes, but they can involve subtleties. If you intend to
use inner classes in any of these other ways, you should consult Section 13.3.
13.3
More about Inner Classes
Something deeply hidden had to be behind things.
ALBERT EINSTEIN, Note quoted in New York Times Magazine (August 2, 1964)
In this section we cover some of the more subtle details about using inner classes. It
might be best to treat this section as a reference section and look up the relevant cases
as you need them. None of the material in this section is used in the rest of this topic.
Static Inner Classes
A normal (nonstatic) inner class, which is the kind of inner class we have discussed so far,
has a connection between each of its objects and the object of the outer class that created
the inner class object. Among other things, this allows an inner class definition to reference
an instance variable or invoke a method of the outer class. If you do not need this connec-
tion, you can make your inner class static by adding the static modifier to your inner
class definition, as illustrated by the following sample beginning of a class definition:
static
public class OuterClass
{
private static class InnerClass
{
A static inner class can have nonstatic instance variables and methods, but an object of
a static inner class has no connection to an object of the outer class.
You may encounter situations where you need an inner class to be static. For exam-
ple, if you create an object of the inner class within a static method of the outer class,
then the inner class must be static. This follows from the fact that a nonstatic inner
class object must arise from an outer class object.
Also, if you want your inner class to itself have static members, then the inner class
must be static.
Since a static inner class has no connection to an object of the outer class, you can-
not reference an instance variable or invoke a nonstatic method of the outer class
within the static inner class.
To invoke a static method of a static inner class within the outer class, simply pref-
ace the method name with the name of the inner class and a dot. Similarly, to name a
Search WWH ::




Custom Search