/* Point3.java */ /* Inheritance demo. What happens if we want to deal with three-dimensional points? We could write a new class from scratch, but why not re-use all that work we did in Point2. In Java you define a subclass with the syntax "[access-specifier] class [subclassname] extends [superclass]". The inheriting class inherits the data members and methods of its parent. It can then add data members, add methods, and _override_ methods (give new definitions to methods with the same name, return type, and parameter list in an ancestral class). In this case Point3 inherits the data members x and y from Point2, and adds z. Accessor methods are added to set and fetch the value of the new member. The constructors are amended so that all the data members are handled correctly (there's some trickery here, a full discussion of which is best left 'til you've read Chapter 4 of Eckel). setPoint() is _overloaded_: we now have a three-argument version of it, in addition to the two-argument one inherited from Point2. print() is _overridden_: that is, when print() is invoked on a Point3 object, the version defined here will be executed, rather than the one (with the same return type and parameter list) defined in Point2 public class Point3 extends Point2 { private int z; /* constructor trickery 1: unless you explicitly specify otherwise, the no-argument constructor of a superclass is automatically called before the subclass constructor is executed; in this case we're letting the superclass constructor handle the initialization of the data members x and y, and we do z by hand */ public Point3() { z = 0; } /* constructor trickery 2: when you want a superclass constructor other than the default, no-argument one to be run, call it as "super([params])" public Point3(int offset) { super(offset); z = offset; } /* ...and by handing different parameter lists to super(), you can force different constructors to be executed */ public Point3(int xVal, int yVal, int zVal) { super(xVal, yVal); z = zVal; } /* notice that in both print() and setPoint() we access the data members defined in Point2 through the accessor methods rather than by referring to x and y directly. In fact we have to do so: x and y are defined in Point2 as "private", which means "private to this class". So either you do what I've done here--set up accessors; or else you use the access-specifier "protected" on x and y, which means (roughly) "private to this class and any descendant classes" */ public void print() { System.out.println("x = " + getX() + ", y = " + getY() + ", z = " + getZ()); } public void setPoint(int xValue, int yValue, int zValue) { setX(xValue); setY(yValue); z = zValue; } public void setZ(int n) { z = n; } public int getZ() { return z; } }