Java Reference
In-Depth Information
Static Nested Classes
To make objects of a nested class type independent of objects of the enclosing class, you can declare the
nested class as static . For example,
public class Outside {
public static class Skinside {
// Details of Skinside
}
// Nested class
public class Inside {
// Details of Inside class...
}
// More members of Outside class...
}
Now with Skinside inside Outside declared as static , we can declare objects of this nested class,
independent from objects of Outside , and regardless of whether we have created any Outside
objects or not. For example:
Outside.Skinside example = new Outside.Skinside();
This is significantly different from what we needed to do for a non-static nested class. Now we must use
the nested class name qualified by the enclosing class name as the type for creating the object. Note that
a static nested class can have static members, whereas a non-static nested class cannot.
class Outside{
Top level class
static members
Members of a static nested
class can access static
members of the
top level class
static class Skinside{
A non-static nested class
can access any members
of the top level class,
regardless of their access
attributes. A non-static
nested class can access
static members of any
static nested classes
within the same top
level class
static members
non-static members
}
A non-static nested class
cannot have static members
class Inside{
non-static members
}
non-static members
}
Let's see how a nested class works in practice with a simple example. We will create a class MagicHat
that will define an object containing a variable number of rabbits. We will put the definition for the class
Rabbit inside the definition of the class MagicHat . The basic structure of MagicHat.java will be:
Search WWH ::




Custom Search