Java Reference
In-Depth Information
Example 8.2-4. Inheritance of private Class Members
Click here to view code image
class Point {
int x, y;
void move(int dx, int dy) {
x += dx; y += dy; totalMoves++;
}
private static int totalMoves;
void printMoves() { System.out.println(totalMoves); }
}
class Point3d extends Point {
int z;
void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz; totalMoves++; // error
}
}
Here, the class variable totalMoves can be used only within the class Point ; it is not in-
herited by the subclass Point3d . A compile-time error occurs because method move of
class Point3d tries to increment totalMoves .
Example 8.2-5. Accessing Members of Inaccessible Classes
Even though a class might not be declared public , instances of the class might be avail-
able at run time to code outside the package in which it is declared by means a public
superclass or superinterface. An instance of the class can be assigned to a variable of
such a public type. An invocation of a public method of the object referred to by such
a variable may invoke a method of the class if it implements or overrides a method
of the public superclass or superinterface. (In this situation, the method is necessarily
declared public , even though it is declared in a class that is not public .)
Consider the compilation unit:
package points;
public class Point {
public int x, y;
public void move(int dx, int dy) {
x += dx; y += dy;
}
}
and another compilation unit of another package:
Search WWH ::




Custom Search