Creating a Subclass

To see an example of inheritance at work, in the next project you create a class called Point3D that 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 Point3D class 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 called Point.

It has two integer variables called x and y that store a Point object’s (x,y) location. It also has a move() method to place a point at the specified location, 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: import java.awt.*;
 2:
 3: public class Point3D extends Point {
 4:     public int z;
 5:
 6:     public Point3D(int x, int y, int z) {
 7:         super(x,y);
 8:         this.z = z;
 9:     }
10:
11:     public void move(int x, int y, int z) {
12:         this.z = z;
13:         super.move(x, y);
14:     }
15:
16:     public void translate(int x, int y, int z) {
17:         this.z += z;
18:         super.translate(x, y);
19:     }
20: }


The Point3D class 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 Point3D class only has to do work that isn’t being done by its superclass, Point. This primarily involves keeping track of the integer variable z and receiving it as an argument to the move() method, translate() method, and Point3D() constructor method.

All the methods use the keywords super and this. The this statement is used to refer to the current Point3D object, so this.z = z; in Line 8 sets the object variable z equal to the z value that is sent as an argument to the method in Line 6.

The super statement refers 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 Point3D object. Because Point already is equipped to handle the x and y axes, it would be redundant for the Point3D class of objects to do the same thing.

To test out the Point3D class you have compiled, create a program that uses Point and Point3D objects and moves them around. Create a new file in NetBeans called PointTester and enter Listing 12.3 into it. The file compiles automatically when it is saved.

Listing 12.3. The Full Text of PointTester.java


 1: import java.awt.*;
 2:
 3: class PointTester {
 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(" It'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(" It'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 + ") ");
19:
20:         System.out.println("The 3D point is located at (" + object2.x
21:             + ", " + object2.y + ", " + object2.z + ")");
22:         System.out.println(" It's being moved to (10, 22, 71)");
23:         object2.move(10,22,71);
24:         System.out.println("The 3D point is now at (" + object2.x
25:             + ", " + object2.y + ", " + object2.z + ")");
26:         System.out.println(" It's being moved -20 units on the x, y "
27:             + "and z axes");
28:         object2.translate(-20,-20,-20);
29:         System.out.println("The 3D point ends up at (" + object2.x
30:             + ", " + object2.y + ", " + object2.z + ")");
31:     }
32: }


When you run the file by choosing Run, Run File, you see the output shown in Figure 12.3 if the program compiled properly. If not, look for the red icon alongside the source editor that indicates the line that triggered an error.

Figure 12.3. The output of the PointTester program.

Image

Summary

When people talk about the miracle of birth, they’re probably not speaking of the way a superclass in Java can give birth to subclasses or the way behavior and attributes are inherited in a hierarchy of classes.

If the real world worked the same way that OOP does, every descendant of Mozart could choose to be a brilliant composer. All descendants of Mark Twain could be poetic about Mississippi riverboat life. Every skill your ancestors worked to achieve would be handed to you without an ounce of toil.

On the scale of miracles, inheritance isn’t quite up to par with continuing the existence of a species or throwing consecutive no-hitters. However, it’s an effective way to design software with a minimum of redundant work.

Q&A

Q. Most Java programs we’ve created up to this point have not used extends to inherit from a superclass. Does this mean they exist outside of the class hierarchy?

A. All classes you create in Java are part of the hierarchy because the default superclass for the programs you write is Object when you aren’t using the extends keyword. The equals() and toString() methods of all classes are part of the behavior that automatically is inherited from Object.

Q. Why do people yell “eureka!” when they’ve discovered something?

A. Eureka is borrowed from ancient Greek, where it meant “I have found it!” The phrase was supposedly exclaimed by the Greek scholar Archimedes when he stepped into a bath.

What did the Greek discover in the bath? The rising water level, which led him to understand that the volume of displaced water must equal the volume of his body parts.

The story about Archimedes was spread two centuries later by Vitruvius in his multivolume De Architectura, a book about architecture.

“Eureka” has been in the California state seal since 1849, referring to the discovery of gold near Sutter’s Mill a year earlier.

Workshop

To determine what kind of knowledge you inherited from the past hour’s work, answer the following questions.

Quiz

1. If a superclass handles a method in a way you don’t want to use in the subclass, what can you do?

A. Delete the method in the superclass.

B. Override the method in the subclass.

C. Write a nasty letter to the editor of the San Jose Mercury News hoping that Java’s developers read it.

2. What methods can you use to retrieve an element stored in a vector?

A. get()

B. read()

C. elementAt()

3. What statement can you use to refer to the methods and variables of the current object?

A. this

B. that

C. theOther

Answers

1. B. Because you can override the method, you don’t have to change any aspect of the superclass or the way it works.

2. A. The get() method has one argument—the index number of the element.

3. A. The this keyword refers to the object in which it appears.

Activities

If a fertile imagination has birthed in you a desire to learn more, you can spawn more knowledge of inheritance with the following activities:

• Create a Point4D class that adds a t coordinate to the (x,y,z) coordinate system created by the Point3D class. The t coordinate stands for time, so you need to ensure that it is never set to a negative value.

• Take the members of a football team’s offense: lineman, wide receiver, tight end, running back, and quarterback. Design a hierarchy of classes that represent the skills of these players, putting common skills higher up in the hierarchy. For example, blocking is behavior that probably should be inherited by the linemen and tight end classes, and speed is something that should be inherited by wide receivers and running backs.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.26.217