Java Reference
In-Depth Information
Nested classes
Thus far, we have said that each class may contain variable declarations and
method definitions, and method bodies may contain local variable declarations.
We have always placed the definition of a class C (say) in a file .
We now state that a class may be defined in another class, and even in a
method body. Such a class is called a nested class . In this section, we explain
why nested classes are useful, explain restrictions on them, and give examples.
Lesson page
Static nested classes
We look first at a static nested class : a class that is declared with attribute stat-
ic within another class. Consider writing a class WireForm , as in Fig. 12.10,
whose instances represent three-dimensional wire models. The model consists of
a bunch of wires, or straight lines.
The components of class WireForm are of no interest in this discussion, and
we have placed three components in it only to illustrate. However, WireForm will
probably use something like class Line , shown also in Fig. 12.10, which has
three fields to describe the beginning of a line and another three to describe the
end of the line. Class Line would be placed in its own file, .
This organization has a big disadvantage. There is a proliferation of classes
for users of WireForm to contend with. Why should users have to see class Line
when it is used only by class WireForm , and not directly by users? In fact, the
designers of WireForm may not want users to see class Line . The principle of
information hiding (see Sec. 3.1.1) says to make visible only what users need to
see, and this principle is violated here.
We can move toward the principle of information hiding by placing the def-
inition of class Line within class WireForm instead of in its own file, as shown
in Fig. 12.11. We make class Line a static class, as shown in Fig. 12.12, so it is
a static nested class .
/** A wire form */
public class WireForm {
public static int x;
private int y;
public int meth(...) {...}
/** An instance represents a line in 3 dimensions */
public class Line {
double x1, y1, z1; // Coordinates of start of line
double x2, y2, z2; // Coordinates of end of line
Program 12.10:
Classes WireForm and Line (in different files)
Search WWH ::

Custom Search