Java Reference
In-Depth Information
Now, there is no need for a file , so that is one less file to deal
with. Moreover, although we can leave class Line public, we prefer to make it
private so that the user cannot refer to it. We have followed the principle of infor-
mation hiding.
Static nested classes and the inside-out rule
Most programming languages adhere to the inside-out rule , which was dis-
cussed in Sec. 3.1.2. You have used this rule already. For example, statements
within the body of method meth (in class WireForm ) can reference variables y
and x , which are declared in the enclosing class. This inside-out rule applies to
static nested classes, as follows:
1. A static nested class may refer to static items of the outer class. Therefore,
within Line , x can be referenced (see Fig. 12.11).
2. A static nested class may not refer to non-static items of the outer class,
so within Line , variable y and method meth may not be referenced.
When to use a static nested class
Here is a general guideline for when to use a static nested class:
If the purpose of a class In is simply to support another class Out
—meaning that In is used only in Out and in no other part of the
program— and if In makes no reference to non-static components
of Out , then make In a static nested class of Out .
Thus, use static nested classes to improve the structure of your program and
to make the program more manageable. Also, use static nested classes to hide
classes that the user need not know about —follow the principle of information
hiding (see Sec. 3.1.1).
/** An instance represents a wire form */
public class WireForm {
public static int x;
private int y;
public int meth(...) {...}
/** An instance represents a line in 3 dimensions */
private static class Line {
double x1, y1, z1; // Coordinates of start of line
double x2, y2, z2; // Coordinates of end of line
Figure 12.11:
Class WireForm with static nested class Line
Search WWH ::

Custom Search