Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Creating a Subclass 165

The Point3Dclass does not have a main()block statement, so you cannot run
it with a Java interpreter, but you can use it in Java programs anywhere a
three-dimensional point is needed.


The Point3Dclass only has to do work that isn’t being done by its superclass,
Point. This primarily involves keeping track of the integer variable zand
receiving it as an argument to the move()method, translate()method, and
Point3D()constructor method.


All the methods use the keywords superand this. The thisstatementis
used to refer to the current Point3Dobject, so this.z = z;in Line 8 sets the
object variable zequal to the zvalue that is sent as an argument to the
method in Line 6.


The superstatementrefers to the current object’s superclass, Point. It is used
to set variables and call methods that are inherited by Point3D. The statement
super(x,y)in Line 7 calls the Point(x,y)constructor in the superclass,
which then sets the (x,y) coordinates of the Point3Dobject. Because Point
already is equipped to handle the x and y axes, it would be redundant for the
Point3Dclass of objects to do the same thing.


To test out the Point3Dclass you have compiled, create a program that uses
Pointand Point3Dobjects and moves them around. Create a new file in
NetBeans called PointTesterand enter Listing 12.3 into it. The file compiles
automatically when it is saved.


LISTING 12.3 The Full Text of PointTester.java
1: importjava.awt.*;
2:
3: classPointTester {
4: public static void main(String[] args) {
5: Point object1 = new Point(11,22);
6: Point3D object2 = new Point3D(7,6,64);
7:
8: System.out.println(“The 2D point is located at (“+ object1.x
9: + “, “+ object1.y + “)”);
10: System.out.println(“\tIt’s being moved to (4, 13)”);
11: object1.move(4,13);
12: System.out.println(“The 2D point is now at (“+ object1.x
13: + “, “+ object1.y + “)”);
14: System.out.println(“\tIt’s being moved -10 units on both the x “
15: + “and y axes”);
16: object1.translate(-10,-10);
17: System.out.println(“The 2D point ends up at (“+ object1.x
18: + “, “+ object1.y + “)\n”);
19:

Free download pdf