Java Reference
In-Depth Information
Click here to view code image
package morePoints;
class Point3d extends points.Point {
public int z;
public void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz;
}
public void move(int dx, int dy) {
move(dx, dy, 0);
}
}
public class OnePoint {
public static points.Point getOne() {
return new Point3d();
}
}
An invocation morePoints.OnePoint.getOne() in yet a third package would return a Point3d
that can be used as a Point , even though the type Point3d is not available outside the
package morePoints . The two-argument version of method move could then be invoked
for that object, which is permissible because method move of Point3d is public (as it must
be, for any method that overrides a public method must itself be public , precisely so that
situations such as this will work out correctly). The fields x and y of that object could
also be accessed from such a third package.
While the field z of class Point3d is public , it is not possible to access this field from
code outside the package morePoints , given only a reference to an instance of class
Point3d in a variable p of type Point . This is because the expression p.z is not correct, as
p has type Point and class Point has no field named z ; also, the expression ((Point3d)p).z
is not correct, because the class type Point3d cannot be referred to outside package
morePoints .
The declaration of the field z as public is not useless, however. If there were to be, in
package morePoints , a public subclass Point4d of the class Point3d :
Click here to view code image
package morePoints;
public class Point4d extends Point3d {
public int w;
public void move(int dx, int dy, int dz, int dw) {
super.move(dx, dy, dz); w += dw;
}
}
Search WWH ::




Custom Search