25. Java Inner Classes

25.2. Nested Top-Level Versus Member Classes

The Converter class (Figure F–1) shows the differences between a nested top- level class and a member class. The program is a somewhat contrived example that performs various kinds of metric conversions. The outer Converter class

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure F–1: A Java application containing a top-level nested class.

 

serves as a container for the inner classes, Distance and Weight, which perform specific conversions.

The Distance class is declared static, so it is a top-level class. It is contained in the Converter class itself. Note the syntax used in ConverterUser.main() to create an instance of the Distance class:

,,

 

J

A fully qualified name is used to refer to the static inner class via its containing class.

The Weight class is not declared static. It is, therefore, associated with in- stances of the Converter class. Note the syntax used to create an instance of the Weight class:

,,

 

J

 

Before you can create an instance of Weight, you have to declare an instance of Converter. In this example, we have used two statements to create the weight object, which requires using the temporary variable, converter, as a reference to the Converter object. We could also have done this with a single statement by using the following syntax:

,,

 

J

Note that in either case the qualified name Converter.Weight must be used to access the inner class from the ConverterUser class.

There are a couple of other noteworthy features in this example. First, an inner top-level class is really just a programming convenience. It behaves just like any other top-level class in Java. One restriction on top-level inner classes is that they can only be contained within other top-level classes, although they can be nested one within the other. For example, we could nest additional converter classes within the Distance class. Java provides special syntax for referring to such nested classes.

Unlike a top-level class, a member class is nested within an instance of its con- taining class. Because of this, it can refer to instance variables (LBS_PER_KG) and instance methods of its containing class, even to those declared private. By con- trast, a top-level inner class can only refer to class variables (INCH_PER_METER)— that is, to variables that are declared static. So you would use a member class if it were necessary to refer to instances of the containing class.

There are many other subtle points associated with member classes, including special language syntax that can be used to refer to nested member classes and rules that govern inheritance and scope of member classes. For these details you should consult the Java Language Specification, which can be accessed online at

,,

 

J