Java Reference
In-Depth Information
Here both classes in the points package compile. The class Point3d inherits the fields x
and y of class Point , because it is in the same package as Point . The class Point4d , which
is in a different package, does not inherit the fields x and y of class Point or the field z
of class Point3d , and so fails to compile.
A better way to write the third compilation unit would be:
Click here to view code image
import points.Point3d;
class Point4d extends Point3d {
int w;
public void move(int dx, int dy, int dz, int dw) {
super.move(dx, dy, dz); w += dw;
}
}
using the move method of the superclass Point3d to process dx , dy , and dz . If Point4d is
written in this way, it will compile without errors.
Example 8.2-3. Inheritance of public and protected Class Members
Given the class Point :
Click here to view code image
package points;
public class Point {
public int x, y;
protected int useCount = 0;
static protected int totalUseCount = 0;
public void move(int dx, int dy) {
x += dx; y += dy; useCount++; totalUseCount++;
}
}
the public and protected fields x , y , useCount , and totalUseCount are inherited in all sub-
classes of Point .
Therefore, this test program, in another package, can be compiled successfully:
Click here to view code image
class Test extends points.Point {
public void moveBack(int dx, int dy) {
x -= dx; y -= dy; useCount++; totalUseCount++;
}
}
Search WWH ::




Custom Search