Chapter 9: Inheritance 153
Chapter 9: Inheritance
Lab Exercises
Topics Lab Exercises
Inheritance Exploring Inheritance
A Sorted Integer List
Test Questions
Overriding the equals Method
154 Chapter 9: Inheritance
Exploring Inheritance
File Dog.java contains a declaration for a Dog class. Save this file to your directory and study it—notice what
instance variables and methods are provided. Files Labrador.java and Yorkshire.java contain declarations for
classes that extend Dog. Save and study these files as well.
File DogTest.java contains a simple driver program that creates a dog and makes it speak. Study DogTest.java,
save it to your directory, and compile and run it to see what it does. Now modify these files as follows:
1. Add statements in DogTest.java after you create and print the dog to create and print a Yorkshire and a
Labrador. Note that the Labrador constructor takes two parameters: the name and color of the labrador,
both strings. Don’t change any files besides DogTest.java. Now recompile DogTest.java; you should get an
error saying something like
If you look at line 18 of Labrador.java it’s just a {, and the constructor the compiler can’t find (Dog()) isn’t
called anywhere in this file.
a. What’s going on? (Hint: What call must be made in the constructor of a subclass?)
2. Add code to DogTest.java to print the average breed weight for both your Labrador and your Yorkshire.
Use the avgBreedWeight() method for both. What error do you get? Why?
=>
3. Add an abstract int avgBreedWeight() method to the Dog class. Remember that this means that the word
abstract appears in the method header after public, and that the method does not have a body (just a
semicolon after the parameter list). It makes sense for this to be abstract, since Dog has no idea what breed
it is. Now any subclass of Dog must have an avgBreedWeight method; since both Yorkshire and Laborador
do, you should be all set.
Chapter 9: Inheritance 155
// ****************************************************************
// Dog.java
//
// A class that holds a dog’s name and can make it speak.
// ————————————————————
// Constructor — store name
// ————————————————————
public Dog(String name)
{
this.name = name;
}
// ————————————————————
// Returns a string with the dog’s comments
156 Chapter 9: Inheritance
// ****************************************************************
// Labrador.java
{
private String color; //black, yellow, or chocolate?
private int breedWeight = 75;
public Labrador(String name, String color)
{
this.color = color;
}
// ————————————————————
// Big bark — overrides speak method in Dog
// ————————————————————
public String speak()
{
return “WOOF”;
Chapter 9: Inheritance 157
public class Yorkshire extends Dog
{
public Yorkshire(String name)
{
super(name);
}
// ————————————————————-
// Small bark — overrides speak method in Dog
// ————————————————————-
public String speak()
// DogTest.java
//
// A simple test class that creates a Dog and makes it speak.
//
// ****************************************************************
158 Chapter 9: Inheritance
A Sorted Integer List
File IntList.java contains code for an integer list class. Save it to your directory and study it; notice that the only
things you can do are create a list of a fixed size and add an element to a list. If the list is already full, a message
will be printed. File ListTest.java contains code for a class that creates an IntList, puts some values in it, and
prints it. Save this to your directory and compile and run it to see how it works.
Now write a class SortedIntList that extends IntList. SortedIntList should be just like IntList except that its
elements should always be in sorted order from smallest to largest. This means that when an element is inserted
into a SortedIntList it should be put into its sorted place, not just at the end of the array. To do this you’ll need to
do two things when you add a new element:
Walk down the array until you find the place where the new element should go. Since the list is already
sorted you can just keep looking at elements until you find one that is at least as big as the one to be
All of this will go into your add method, which will override the add method for the IntList class. (Be sure to
also check to see if you need to expand the array, just as in the IntList add method.) What other methods, if any,
do you need to override?
To test your class, modify ListTest.java so that after it creates and prints the IntList, it creates and prints a
SortedIntList containing the same elements (inserted in the same order). When the list is printed, they should
come out in sorted order.
// ****************************************************************
// IntList.java
//
{
protected int[] list;
protected int numElements = 0;
//————————————————————-
// Constructor — creates an integer list of a given size.
//————————————————————-
public IntList(int size)
{
list = new int[size];
System.out.println(“Can’t add, list is full”);
else
{
list[numElements] = value;
numElements++;
Chapter 9: Inheritance 159
}
}
for (int i=0; i<numElements; i++)
returnString += i + “: ” + list[i] + “\n”;
return returnString;
}
}
// ***************************************************************
public class ListTest
{
public static void main(String[] args)
{
160 Chapter 9: Inheritance
Test Questions
In this exercise you will use inheritance to read, store, and print questions for a test. First, write an abstract class
TestQuestion that contains the following:
A protected String variable that holds the test question.
An abstract method protected abstract void readQuestion() to read the question.
Now define two subclasses of TestQuestion, Essay and MultChoice. Essay will need an instance variable to
store the number of blank lines needed after the question (answering space). MultChoice will not need this
variable, but it will need an array of Strings to hold the choices along with the main question. Assume that
the input is provided from the standard input as follows, with each item on its own line:
type of question (character, m=multiple choice, e=essay)
The very first item of input, before any questions, is an integer indicating how many questions will be
entered. So the following input represents three questions: an essay question requiring 5 blank lines, a
multiple choice question with 4 choices, and another essay question requiring 10 blank lines:
3
e
5
_guess2_
Guess
e
5
What does the “final” modifier do?
You will need to write readQuestion methods for the MultChoice and Essay classes that read information
in this format. (Presumably the character that identifies what kind of question it is will be read by a driver.)
You will also need to write toString methods for the MultChoice and Essay classes that return nicely
formatted versions of the questions (e.g., the choices should be lined up, labeled a), b), etc, and indented in
MultChioce).
Now define a class WriteTest that creates an array of TestQuestion objects. It should read the questions
from the standard input as follows in the format above, first reading an integer that indicates how many
questions are coming. It should create a MultChoice object for each multiple choice question and an Essay
object for each essay question and store each object in the array. (Since it’s an array of TestQuestion and
both Essay and MultChoice are subclasses of TestQuestion, objects of both types can be stored in the
array.) When all of the data has been read, it should use a loop to print the questions, numbered, in order.
Use the data in testbank.dat to test your program.
Chapter 9: Inheritance 161
guess2
2ndGuess
_guess2_
Guess
e
5
What does the “final” modifier do?
e
3
Java does not support multiple inheritance. This means that a class cannot do
what?
m
162 Chapter 9: Inheritance
Overriding the equals Method
File Player.java contains a class that holds information about an athlete: name, team, and uniform number. File
ComparePlayers.java contains a skeletal program that uses the Player class to read in information about two
baseball players and determine whether or not they are the same player.
1. Fill in the missing code in ComparePlayers so that it reads in two players and prints “Same player” if they
are the same, “Different players” if they are different. Use the equals method, which Player inherits from
the Object class, to determine whether two players are the same. Are the results what you expect?
2. The problem above is that as defined in the Object class, equals does an address comparison. It says that
two objects are the same if they live at the same memory location, that is, if the variables that hold
references to them are aliases. The two Player objects in this program are not aliases, so even if they
contain exactly the same information they will be “not equal.” To make equals compare the actual
information in the object, you can override it with a definition specific to the class. It might make sense to
say that two players are “equal” (the same player) if they are on the same team and have the same uniform
// *********************************************************
// Player.java
//
import java.util.Scanner;
public class Player
{
private String name;
private String team;
private int jerseyNumber;
System.out.print(“Jersey number: “);
jerseyNumber = Scan.nextInt();
}
}
Chapter 9: Inheritance 163
// **************************************************************
// ComparePlayers
//
//Prompt for and read in information for player 2
//Compare player1 to player 2 and print a message saying
//whether they are equal
}
}
164 Chapter 9: Inheritance
Extending Adapter Classes
Files Dots.java and DotsPanel.java contain the code in Listings 7.18 and 7.19 of the text. This program draws
dots where the user clicks and counts the number of dots that have been drawn. Save these files to your
directory and compile and run Dots to see how it works.
Now study the code in DotsPanel.java. (Dots just creates an instance of DotsPanel and adds it to its content
pane.) DotsPanel defines an inner class, DotsListener, that implements the MouseListener interface. Notice that
it defines the mousePressed method to draw a dot at the click point and gives empty bodies for the rest of the
MouseListener methods.
1. Modify the DotsListener class so that instead of implementing the MouseListener interface, it extends the
MouseAdapter class. What other code does this let you eliminate? For now, just comment out this code. Test
2. We have been using inner classes to define event listeners. Another common strategy is to make the panel
itself be a MouseListener, eliminating the need for the inner class. Do this as follows:
Modify the header to the DotsPanel class to indicate that it implements the MouseListener interface (it
still extends JPanel).
Delete the DotsListener class entirely, moving the five MouseListener methods into the DotsPanel class.
The DotsPanel constructor contains the following statement:
3. When we were using the DotsListener class we saw that it could either implement the MouseListener
interface or extend the MouseAdapter class. With the new approach in #2, where the DotsPanel is also a
MouseListener, can we do the same thing – that is, can DotsPanel extend MouseAdapter instead of
implementing MouseListener? Why or why not? If you’re not sure, try it and explain what happens.
//*******************************************************************
// Dots.java Author: Lewis/Loftus
//
// Demonstrates mouse events.
//*******************************************************************
frame.getContentPane().add (new DotsPanel());
frame.pack();
frame.setVisible(true);
}
}
Chapter 9: Inheritance 165
//*******************************************************************
// DotsPanel.java Author: Lewis/Loftus
//
// Represents the primary panel for the Dots program.
//*******************************************************************
{
private final int SIZE =6; // radius of each dot
private ArrayList<Point> pointList;
//—————————————————————–
// Constructor: Sets up this panel to listen for mouse events.
//—————————————————————–
public DotsPanel()
{
pointList = new ArrayList<Point>();
//—————————————————————-
// Draws all of the dots stored in the list.
//—————————————————————-
public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.setColor (Color.green);
for (Point spot: pointList)
page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
page.drawString (“Count: ” + pointList.size(), 5, 15);
}
pointList.add(event.getPoint());
repaint();
}
166 Chapter 9: Inheritance
//—————————————————————-
// Provide empty definitions for unused event methods.
//—————————————————————-
public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
}
Chapter 9: Inheritance 167
Rebound Revisited
The files Rebound.java and ReboundPanel.java contain the program are in Listings 8.15 and 8.16 of the text. This program
has an image that moves around the screen, bouncing back when it hits the sides (you can use any GIF or JPEG you like).
Save these files to your directory, then open ReboundPanel.java in the editor and observe the following:
The constructor instantializes a Timer object with a delay of 20 (the time, in milliseconds, between
generation of action events). The Timer object is started with its start method.
Now do the following:
1. First experiment with the speed of the animation. This is affected by two things—the value of the DELAY
constant and the amount the ball is moved each time.
Change DELAY to 100. Save, compile, and run the program. How does the speed compare to the original?
2. Now add a second image to the program by doing the following:
Declare a second ImageIcon object as an instance variable. You can use the same image as before or a new one.
Declare integer variables x2 and y2 to represent the location of the second image, and moveX2 and
2. Compile and run the program. Make sure it is working correctly.
//********************************************************************
// Rebound.java Author: Lewis/Loftus
//
// Demonstrates an animation and the use of the Timer class.
//********************************************************************
frame.getContentPane().add(new ReboundPanel());
frame.pack();
frame.setVisible(true);
}
}
//*********************************************************************
private Timer timer;
private int x, y, moveX, moveY;
//——————————————————————
// Sets up the panel, including the timer for the animation.
//——————————————————————
// Draws the image in the current location.
//—————————————————————–
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
Count Down
Clocks are a standard thing to animate—they change at regular intervals. In this exercise, you will write an
applet that displays a simple “clock” that just counts down from 10. The clock will be a DigitalDisplay object.
The file DigitalDisplay.java contains the code for the class. The file CountDown.java contains the program and
CountDownPanel.java contains a skeleton for the panel for the animation. Copy these files to your directory,
compile and run the program. It should just display the clock with the number 10. Now do the following to
make the clock count down, stop when it hits 0, and reset to 10 if the user clicks the mouse.
1. Add an inner class named CountListener that implements ActionListener. In actionPerformed,
2. In the constructor, set up the timer.
4. Now add code to let a mouse click have some control over the clock. In particular, if the clock is running
when the mouse is clicked the clock should be stopped (stop the timer). If the clock is not running, it should
be reset to 10 and started. To add the ability of the panel to respond to mouse clicks, do the following:
5. Compile and run the program to make sure everything works right.
//***************************************************
// DigitalDisplay.java
//
// A simple rectangular display of a single number
//***************************************************
public DigitalDisplay(int start, int x, int y, int w, int h)
{
this.x = x;
this.y = y;
width = w;
height = h;
170 Chapter 9: Inheritance
// —————————-
public void increment()
{
displayVal++;
}
// —————————-
// return the display value
// —————-
public void draw (Graphics page)
{
// draw a black border
page.setColor (Color.black);
page.fillRect (x, y, width, height);
}
}
// **********************************************************
// CountDown.java
//
// Draws a digital display that counts down from 10. The
// display can be stopped or reset with a mouse click.
// ———————————————————
public void init()
{
timer = new Timer (DELAY, null);
getContentPane().add (new CountDownPanel(timer));
}
// ———————————————————
// **********************************************************
// CountDownPanel.java
//
// Panel for a digital display that counts down from 10.
// The display can be stopped or reset with a mouse click.
// **********************************************************
private final int COUNT_START = 10;
private DigitalDisplay clock;
private Timer timer;
// ——————————————————–
// Set up the applet.