ptg7068951
164 HOUR 12:Making the Most of Existing Objects
Creating a Subclass
To see anexample of inheritance at work, in the next project you create a class
called Point3Dthat represents a point in three-dimensional space. You can
express a two-dimensional point with an (x,y) coordinate. Applets use an (x,y)
coordinate system to determine where text and graphics should be displayed.
Three-dimensional space adds a third coordinate, which can be called z.
The Point3Dclass of objects should do three things:
. Keep track of an object’s (x,y,z) coordinate
. Move an object to a new (x,y,z) coordinate when needed
. Move an object by a certain amount of x, y, and z values as needed
Java already has a standard class that represents two-dimensional points;
it’s calledPoint.
It has two integer variables called xand ythat store a Pointobject’s (x,y)
location. It also has a move()method to place a point at the specified loca-
tion, and a translate()method to move an object by an amount of x and y
values.
In the Java24 projects in NetBeans, create a new empty file called Point3D
and enter the text of Listing 12.2 into the file. Save it when you’re done.
LISTING 12.2 The Full Text of Point3D.java
1: importjava.awt.*;
2:
3: public classPoint3D extendsPoint {
4: publicint z;
5:
6: publicPoint3D(int x, int y, int z) {
7: super(x,y);
8: this.z = z;
9: }
10:
11: public voidmove(int x, int y, int z) {
12: this.z = z;
13: super.move(x, y);
14: }
15:
16: public voidtranslate(int x, int y, int z) {
17: this.z += z;
18: super.translate(x, y);
19: }
20: }