Java Reference
In-Depth Information
A static member class is not an inner class. It is considered a top-level class. It is also called a nested top-level
class. Since it is a top-level class, you do not need an instance of its enclosing class to create its object. An instance of
class
A
and an instance of class
B
can exist independently because both are top-level classes. A static member class
can be declared
public
,
protected
, package-level, or
private
to restrict its accessibility outside its enclosing class.
What is the use of a static member class if it is nothing but another top-level class? There are two advantages of
using a static member class:
•
A static member class can access the static members of its enclosing class including the
private
static members. In your example, if class
A
has any static members, those static
members can be accessed inside class
B
. However, class
B
cannot access any instance
members of class
A
because an instance of class
B
can exist without an instance of class
A
.
A package acts like a container for top-level classes by providing a namespace. Within a
•
namespace, all entities must have unique names. Top-level classes having static member
classes provide an additional layer of namespaces. A static member class is the direct member
of its enclosing top-level class, not a member of the package in which it is declared. In your
example, class
A
is a member of the package
com.jdojo.innerclasses
, whereas class
B
is a
member of class
A
. The fully qualified name of class
A
is
com.jdojo.innerclasses.A
. The fully
qualified name of class
B
is
com.jdojo.innerclasses.A.B
. This way, a top-level class can be
used to group together related classes defined as its static member classes.
An object of a static member class is created the same way as you create an object of a top-level class using the
new
operator. To create an object of class
B
, you write
A.B bReference = new A.B();
Since the simple name of class
B
is in the scope inside class
A
, you can use its simple name to create its object
inside class
A
as
B bReference2 = new B(); // This statement appears inside class A code
You can also use the simple name
B
outside class
A
by importing the
com.jdojo.innerclasses.A.B
class.
However, using the simple name
B
outside class
A
is not intuitive. It gives an impression to the reader that class
B
is a
top-level class, not a nested top-level class. You should use
A.B
for class
B
outside class
A
for better readability.
Listing 2-10 declares two static member classes,
Monitor
and
Keyboard
, which have
ComputerAccessory
as their
enclosing class. Listing 2-11 shows how to create objects of these static member classes.
Listing 2-10.
An Example of Declaring Static Member Classes
// ComputerAccessory.java
package com.jdojo.innerclasses;
public class ComputerAccessory {
// Static member class - Monitor
public static class Monitor {
private int size;
public Monitor(int size) {
this.size = size;
}