Tải bản đầy đủ (.pdf) (91 trang)

Java software solutions foundations of program design 4th edition phần 5 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (802.92 KB, 91 trang )

366 CHAPTER 6 arrays
This program also uses the Font class, which represents a particular character
font. A Font object is defined by the font name, the font style, and the font size.
The font name establishes the general visual characteristics of the characters. We
are using the Helvetica font in this program. The style of a Java font can be plain,
bold, italic, or bold and italic combined. The check boxes in our graphical user
interface are set up to change the characteristics of our font style.
The style of a font is represented as an integer, and integer constants defined
in the
Font class are used to represent the various aspects of the style. The con-
listing
6.19 continued
//
// Returns the primary panel containing the GUI.
//
public JPanel getPanel()
{
return primary;
}
//*****************************************************************
// Represents the listener for both check boxes.
//*****************************************************************
private class StyleListener implements ItemListener
{
//
// Updates the style of the label font style.
//
public void itemStateChanged (ItemEvent event)
{
int style = Font.PLAIN;
if (bold.isSelected())


style = Font.BOLD;
if (italic.isSelected())
style += Font.ITALIC;
saying.setFont (new Font ("Helvetica", style, FONT_SIZE));
}
}
}
6.6 other button components 367
stant PLAIN is used to represent a plain style. The constants BOLD and ITALIC are
used to represent bold and italic, respectively. The sum of the BOLD and ITALIC
constants indicates a style that is both bold and italic.
The itemStateChanged method of the listener determines what the revised
style should be now that one of the check boxes has changed state. It initially sets
the style to be plain. Then each check box is consulted in turn using the
isSelected method, which returns a boolean value. First, if the bold check box
is selected (checked), then the style is set to bold. Then, if the italic check box is
selected, the ITALIC constant is added to the style variable. Finally, the font of
the label is set to a new font with its revised style.
Note that, given the way the listener is written in this program, it doesn’t mat-
ter which check box was clicked to generate the event. Both check boxes are
processed by the same listener. It also doesn’t matter whether the changed check
box was toggled from selected to unselected or vice versa. The state of both check
boxes is examined if either is changed.
radio buttons
A radio button is used with other radio buttons to provide
a set of mutually exclusive options. Unlike a check box, a
radio button is not useful by itself. It has meaning only
when it is used with one or more other radio buttons. Only
one option out of the group is valid. At any point in time,
one and only one button of the group of radio buttons is

selected (on). When a radio button from the group is
pushed, the other button in the group that is currently on is
automatically toggled off.
The term radio buttons comes from the way the buttons worked on an old-
fashioned car radio. At any point, one button was pushed to specify the current
choice of station; when another was pushed, the current one automatically
popped out.
The QuoteOptions program, shown in Listing 6.20, displays a label and a
group of radio buttons. The radio buttons determine which quote is displayed in
the label. Because only one of the quotes can be displayed at a time, the use of
radio buttons is appropriate. For example, if the Comedy radio button is selected,
the comedy quote is displayed in the label. If the Philosophy button is then
pressed, the Comedy radio button is automatically toggled off and the comedy
quote is replaced by a philosophical one.
Radio buttons operate as a
group, providing a set of mutu-
ally exclusive options. When
one button is selected, the cur-
rently selected button is tog-
gled off.
key
concept
368 CHAPTER 6 arrays
listing
6.20
//********************************************************************
// QuoteOptions.java Author: Lewis/Loftus
//
// Demonstrates the use of radio buttons.
//********************************************************************

import javax.swing.*;
public class QuoteOptions
{
//
// Creates and presents the program frame.
//
public static void main (String[] args)
{
JFrame quoteFrame = new JFrame ("Quote Options");
quoteFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
QuoteGUI gui = new QuoteGUI();
quoteFrame.getContentPane().add (gui.getPanel());
quoteFrame.pack();
quoteFrame.show();
}
}
display
6.6 other button components 369
The structure of this program is similar to that of the StyleOptions program
from the previous section. The label and radio buttons are displayed on a panel
defined in the QuoteGUI class, shown in Listing 6.21. A radio button is repre-
sented by the JRadioButton class. Because the radio buttons in a set work
together, the ButtonGroup class is used to define a set of related radio buttons.
listing
6.21
//********************************************************************
// QuoteGUI.java Author: Lewis/Loftus
//
// Represents the user interface for the QuoteOptions program.
//********************************************************************

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class QuoteGUI
{
private final int WIDTH = 300, HEIGHT = 100;
private JPanel primary;
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote = "Take my wife, please.";
private String philosophyQuote = "I think, therefore I am.";
private String carpentryQuote = "Measure twice. Cut once.";
//
// Sets up a panel with a label and a set of radio buttons
// that control its text.
//
public QuoteGUI()
{
quote = new JLabel (comedyQuote);
quote.setFont (new Font ("Helvetica", Font.BOLD, 24));
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
370 CHAPTER 6 arrays
listing
6.21 continued
ButtonGroup group = new ButtonGroup();

group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
primary = new JPanel();
primary.add (quote);
primary.add (comedy);
primary.add (philosophy);
primary.add (carpentry);
primary.setBackground (Color.green);
primary.setPreferredSize (new Dimension(WIDTH, HEIGHT));
}
//
// Returns the primary panel containing the GUI.
//
public JPanel getPanel()
{
return primary;
}
//*****************************************************************
// Represents the listener for all radio buttons
//*****************************************************************
private class QuoteListener implements ActionListener
{
//
// Sets the text of the label depending on which radio
// button was pressed.

//
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
6.6 other button components 371
Note that each button is added to the button group, and also that each button
is added individually to the panel. A ButtonGroup object is not a container to
organize and display components; it is simply a way to define the group of radio
buttons that work together to form a set of dependent options. The ButtonGroup
object ensures that the currently selected radio button is turned off when another
in the group is selected.
A radio button produces an action event when it is selected. The
actionPerformed method of the listener first determines the source of the event
using the getSource method, and then compares it to each of the three radio but-
tons in turn. Depending on which button was selected, the text of the label is set
to the appropriate quote.
Note that unlike push buttons, both check boxes and radio buttons are toggle
buttons, meaning that at any time they are either on or off. The difference is in
how they are used. Independent options (choose any combination) are controlled
with check boxes. Dependent options (choose one of a set) are controlled with
radio buttons. If there is only one option to be managed, a check box can be used
by itself. As we mentioned earlier, a radio button, on the other hand, makes sense
only in conjunction with one or more other radio buttons.
Also note that check boxes and radio buttons produce different types of
events. A check box produces an item event and a radio button produces an
action event. The use of different event types is related to the differences in but-
ton functionality. A check box produces an event when it is selected or deselected,
and the listener could make the distinction if desired. A radio button, on the other
hand, only produces an event when it is selected (the currently selected button
from the group is deselected automatically).

listing
6.21 continued
if (source == comedy)
quote.setText (comedyQuote);
else
if (source == philosophy)
quote.setText (philosophyQuote);
else
quote.setText (carpentryQuote);
}
}
}
372 CHAPTER 6 arrays
◗ An array of size N is indexed from 0 to N–1.
◗ In Java, an array is an object. Memory space for the array elements is
reserved by instantiating the array using the
new operator.
◗ Bounds checking ensures that an index used to refer to an array element is
in range. The Java index operator performs automatic bounds checking.
◗ An initializer list can be used to instantiate an array object instead of
using the
new operator. The size of the array and its initial values are
determined by the initializer list.
◗ An entire array can be passed as a parameter, making the formal parame-
ter an alias of the original.
◗ Command-line arguments are stored in an array of String objects and
are passed to the main method.
◗ Instantiating an array of objects reserves room to store references only.
The objects that are stored in each element must be instantiated
separately.

◗ Selection sort and insertion sort are two sorting algorithms that define the
processing steps for putting a list of values into a well-defined order.
◗ Selection sort works by putting each value in its final position, one at a
time.
◗ Swapping is the process of exchanging two values. Swapping requires
three assignment statements.
◗ Insertion sort works by inserting each value into a previously sorted sub-
set of the list.
◗ Sorting algorithms are ranked according to their efficiency, which is usu-
ally defined as the number of comparisons required to perform the sort.
◗ Both selection sort and insertion sort algorithms are of order n
2
. Other
sorts are more efficient.
◗ Using an array with more than two dimensions is rare in an object-ori-
ented system because intermediate levels are usually represented as sepa-
rate objects.
◗ Each array in a given dimension of a multidimensional array could have a
different length.
summary of
key concepts
self-review questions 373
◗ An ArrayList object is similar to an array, but it dynamically changes
size as needed, and elements can be inserted and removed.
◗ ArrayList processing can be inefficient depending on how it is used.
◗ A polygon is always a closed shape. The last point is automatically con-
nected back to the first one.
◗ A polyline is similar to a polygon except that a polyline is not a closed
shape.
◗ A check box allows the user to set the status of a boolean condition.

◗ Radio buttons operate as a group, providing a set of mutually exclusive
options. When one button is selected, the currently selected button is tog-
gled off.
self-review questions
6.1 Explain the concept of array bounds checking. What happens when
a Java array is indexed with an invalid value?
6.2 Describe the process of creating an array. When is memory allocated
for the array?
6.3 What is an off-by-one error? How does it relate to arrays?
6.4 What does an array initializer list accomplish?
6.5 Can an entire array be passed as a parameter? How is this accom-
plished?
6.6 How is an array of objects created?
6.7 What is a command-line argument?
6.8 What are parallel arrays?
6.9 Which is better: selection sort or insertion sort? Explain.
6.10 How are multidimensional arrays implemented in Java?
6.11 What are the advantages of using an ArrayList object as opposed
to an array? What are the disadvantages?
6.12 What is a polyline? How do we specify its shape?
6.13 Compare and contrast check boxes and radio buttons.
6.14 How does the Timer class help us perform animations in Java?
374 CHAPTER 6 arrays
exercises
6.1 Which of the following are valid declarations? Which instantiate an
array object? Explain your answers.
int primes = {2, 3, 4, 5, 7, 11};
float elapsedTimes[] = {11.47, 12.04, 11.72, 13.88};
int[] scores = int[30];
int[] primes = new {2,3,5,7,11};

int[] scores = new int[30];
char grades[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘f’};
char[] grades = new char[];
6.2 Describe five programs that are difficult to implement without using
arrays.
6.3 Describe what problem occurs in the following code. What modifica-
tions should be made to it to eliminate the problem?
int[] numbers = {3, 2, 3, 6, 9, 10, 12, 32, 3, 12, 6};
for (int count = 1; count <= numbers.length; count++)
System.out.println (numbers[count]);
6.4 Write an array declaration and any necessary supporting classes to
represent the following statements:
◗ students’ names for a class of 25 students
◗ students’ test grades for a class of 40 students
◗ credit-card transactions that contain a transaction number, a mer-
chant name, and a charge
◗ students’ names for a class and homework grades for each student
◗ for each employee of the L&L International Corporation: the
employee number, hire date, and the amount of the last five raises
6.5 Write a method called sumArray that accepts an array of floating
point values and returns the sum of the values stored in the array.
6.6 Write a method called switchThem that accepts two integer arrays
as parameters and switches the contents of the arrays. Take into
account that the arrays may be of different sizes.
6.7 Describe a program for which you would use the ArrayList class
instead of arrays to implement choices. Describe a program for
which you would use arrays instead of the ArrayList class. Explain
your choices.
programming projects 375
6.8 Explain what would happen if the radio buttons used in the

QuoteOptions program were not organized into a ButtonGroup
object. Modify the program to test your answer.
programming projects
6.1 Design and implement an application that reads an arbitrary number
of integers that are in the range 0 to 50 inclusive and counts how
many occurrences of each are entered. After all input has been
processed, print all of the values (with the number of occurrences)
that were entered one or more times.
6.2 Modify the program from Programming Project 6.1 so that it works
for numbers in the range between –25 and 25.
6.3 Rewrite the Sorts class so that both sorting algorithms put the val-
ues in descending order. Create a driver class with a main method to
exercise the modifications.
6.4 Design and implement an application that creates a histogram that
allows you to visually inspect the frequency distribution of a set of
values. The program should read in an arbitrary number of integers
that are in the range 1 to 100 inclusive; then produce a chart similar
to the one below that indicates how many input values fell in the
range 1 to 10, 11 to 20, and so on. Print one asterisk for each value
entered.
6.5 The lines in the histogram in Programming Project 6.4 will be too
long if a large number of values is entered. Modify the program so
that it prints an asterisk for every five values in each category. Ignore
1 - 10 | *****
11 - 20 | **
21 - 30 | *******************
31 - 40 |
41 - 50 | ***
51 - 60 | ********
61 - 70 | **

71 - 80 | *****
81 - 90 | *******
91 - 100 | *********
376 CHAPTER 6 arrays
leftovers. For example, if a category had 17 values, print three aster-
isks in that row. If a category had 4 values, do not print any aster-
isks in that row.
6.6 Design and implement an application that computes and prints the
mean and standard deviation of a list of integers x
1
through x
n
.
Assume that there will be no more than 50 input values. Compute
both the mean and standard deviation as floating point values, using
the following formulas.
mean =
sd =
Ί

6.7 The L&L Bank can handle up to 30 customers who have savings
accounts. Design and implement a program that manages the
accounts. Keep track of key information and allow each customer to
make deposits and withdrawals. Produce appropriate error messages
for invalid transactions. Hint: you may want to base your accounts
on the Account class from Chapter 4. Also provide a method to add
3 percent interest to all accounts whenever the method is invoked.
6.8 Modify the GradeRange program from this chapter so that it elimi-
nates the use of parallel arrays. Instead, design a new class called
Grade that stores both the grade string and its cutoff value. Set both

values using the
Grade constructor and provide methods that return
the values. In the main method of the revised GradeRange program,
populate a single array with
Grade objects, and then produce the
same output as the original
GradeRange program did.
6.9 The programming projects of Chapter 4 discussed a Card class that
represents a standard playing card. Create a class called
DeckOfCards that stores 52 objects of the Card class. Include meth-
ods to shuffle the deck, deal a card, and report the number of cards
left in the deck. The shuffle method should assume a full deck.
Α
n
i = 1
(x
i
– mean)
2
ᎏᎏ
n – 1
Α
n
i = 1
x
i

n
programming projects 377
Create a driver class with a main method that deals each card from a

shuffled deck, printing each card as it is dealt.
6.10 Use the Question class from Chapter 5 to define a Quiz class. A
quiz can be composed of up to 25 questions. Define the add method
of the Quiz class to add a question to a quiz. Define the giveQuiz
method of the Quiz class to present each question in turn to the user,
accept an answer for each one, and keep track of the results. Define
a class called QuizTime with a main method that populates a quiz,
presents it, and prints the final results.
6.11 Modify your answer to Programming Project 6.10 so that the com-
plexity level of the questions given in the quiz is taken into account.
Overload the giveQuiz method so that it accepts two integer
parameters that specify the minimum and maximum complexity lev-
els for the quiz questions and only presents questions in that com-
plexity range. Modify the main method to demonstrate this feature.
6.12 Modify the Tunes program so that it keeps the CDs sorted by title.
Use the general object sort defined in the Sorts class from this
chapter.
6.13 Modify the Sorts class to include an overloaded version of the
SelectionSort method that performs a general object sort. Modify
the SortPhoneList program to test the new sort.
6.14 Design and implement an applet that graphically displays the pro-
cessing of a selection sort. Use bars of various heights to represent
the values being sorted. Display the set of bars after each swap. Put
a delay in the processing of the sort to give the human observer a
chance to see how the order of the values changes.
6.15 Repeat Programming Project 6.14 using an insertion sort.
6.16 Design a class that represents a star with a specified radius and
color. Use a filled polygon to draw the star. Design and implement
an applet that draws 10 stars of random radius in random locations.
6.17 Design a class that represents the visual representation of a car. Use

polylines and polygons to draw the car in any graphics context and
at any location. Create a main driver to display the car.
6.18 Modify the solution to Programming Project 6.17 so that it uses the
Polygon class to represent all polygons used in the drawing.
6.19 Modify the Fahrenheit program from Chapter 5 so that it uses a
structure similar to the StyleOptions and QuoteOptions programs
378 CHAPTER 6 arrays
from this chapter. Specifically, create the application frame in the
main method and add the GUI panel to it.
6.20 Modify the StyleOptions program in this chapter to allow the user
to specify the size of the font. Use a text field to obtain the size.
6.21 Modify the QuoteOptions program in this chapter so that it pro-
vides three additional quote options. Use an array to store all of the
quote strings.
6.22 Design and implement an applet that draws 20 circles, with the
radius and location of each circle determined at random. If a circle
does not overlap any other circle, draw that circle in black. If a circle
overlaps one or more other circles, draw it in cyan. Use an array to
store a representation of each circle, then determine the color of each
circle. Two circles overlap if the distance between their center points
is less than the sum of their radii.
6.23 Design and implement an applet that draws a checkerboard with five
red and eight black checkers on it in various locations. Store the
checkerboard as a two-dimensional array.
6.24 Modify the applet from Programming Project 6.23 so that the pro-
gram determines whether any black checkers can jump any red
checkers. Under the checkerboard, print (using drawString) the row
and column position of all black checkers that have possible jumps.
answers to self-review questions
6.1 Whenever a reference is made to a particular array element, the

index operator (the brackets that enclose the subscript) ensures that
the value of the index is greater than or equal to zero and less than
the size of the array. If it is not within the valid range, an
ArrayIndexOutOfBoundsException is thrown.
6.2 Arrays are objects. Therefore, as with all objects, to create an array
we first create a reference to the array (its name). We then instantiate
the array itself, which reserves memory space to store the array ele-
ments. The only difference between a regular object instantiation
and an array instantiation is the bracket syntax.
6.3 An off-by-one error occurs when a program’s logic exceeds the
boundary of an array (or similar structure) by one. These errors
include forgetting to process a boundary element as well as attempt-
answers to self-review questions 379
ing to process a nonexistent element. Array processing is susceptible
to off-by-one errors because their indexes begin at zero and run to
one less than the size of the array.
6.4 An array initializer list is used in the declaration of an array to set
up the initial values of its elements. An initializer list instantiates the
array object, so the new operator is needed.
6.5 An entire array can be passed as a parameter. Specifically, because an
array is an object, a reference to the array is passed to the method.
Any changes made to the array elements will be reflected outside of
the method.
6.6 An array of objects is really an array of object references. The array
itself must be instantiated, and the objects that are stored in the
array must be created separately.
6.7 A command-line argument is data that is included on the command
line when the interpreter is invoked to execute the program.
Command-line arguments are another way to provide input to a
program. They are accessed using the array of strings that is passed

into the main method as a parameter.
6.8 Parallel arrays are two or more arrays whose corresponding elements
are related in some way. Because parallel arrays can easily get out of
synch if not managed carefully, it is often better to create a single
array of objects that encapsulate the related elements.
6.9 Selection sort and insertion sort are generally equivalent in efficiency,
because they both take about n
2
number of comparisons to sort a
list of n numbers. Selection sort, though, generally makes fewer
swaps. Several sorting algorithms are more efficient than either of
these.
6.10 A multidimensional array is implemented in Java as an array of
array objects. The arrays that are elements of the outer array could
also contain arrays as elements. This nesting process could continue
for as many levels as needed.
6.11 An ArrayList keeps the indexes of its objects continuous as they
are added and removed, and an ArrayList dynamically increases its
capacity as needed. In addition, an ArrayList is implemented so
that it stores references to the Object class, which allows any object
to be stored in it. A disadvantage of the ArrayList class is that it
380 CHAPTER 6 arrays
copies a significant amount of data in order to insert and delete ele-
ments, and this process is inefficient.
6.12 A polyline is defined by a series of points that represent its vertices.
The drawPolyline method takes three parameters to specify its
shape. The first is an array of integers that represent the x coordi-
nates of the points. The second is an array of integers that represent
the y coordinates of the points. The third parameter is a single inte-
ger that indicates the number of points to be used from the arrays.

6.13 Both check boxes and radio buttons show a toggled state: either on
or off. However, radio buttons work as a group in which only one
can be toggled on at any point in time. Check boxes, on the other
hand, represent independent options. They can be used alone or in a
set in which any combination of toggled states is valid.
6.14 The Timer class represents an object that generates an action event
at regular intervals. The programmer sets the interval delay. An ani-
mation can be set up to change its display every time the timer goes
off.
the way we design object-
oriented software. Furthermore,
inheritance enhances our ability
to reuse classes in other situa-
tions and programs. We explore
how classes can be related to
form inheritance hierarchies and
how these relationships allow us
to create polymorphic refer-
ences. This chapter also revisits
the concept of a formal Java
interface. Finally, we discuss
how inheritance affects various
issues related to graphical user
interfaces (GUIs) in Java.
◗ Derive new classes from existing
ones.
◗ Explain how inheritance supports
software reuse.
◗ Add and modify methods in child
classes.

◗ Discuss how to design class
hierarchies.
◗ Define polymorphism and deter-
mine how it can be accomplished.
◗ Examine inheritance hierarchies for
interfaces.
◗ Discuss the use of inheritance in
Java GUI frameworks.
◗ Examine and use the GUI compo-
nent class hierarchy.
chapter
objectives
This chapter explains inheritance, a fundamental
technique for organizing and creating classes. It is
a simple but powerful idea that influences
7
inheritance
382 CHAPTER 7 inheritance
7.0 creating subclasses
In Chapter 4 we presented the analogy that a class is to an object as a blueprint
is to a house. A class establishes the characteristics and behaviors of an object but
reserves no memory space for variables (unless those variables are declared as
static). Classes are the plan, and objects are the embodiment of that plan.
Many houses can be created from the same blueprint. They are essentially the
same house in different locations with different people living in them. But sup-
pose you want a house that is similar to another but with some different or addi-
tional features. You want to start with the same basic blueprint but modify it to
suit your needs and desires. Many housing developments are created this way.
The houses in the development have the same core layout, but they have unique
features. For instance, they might all be split-level homes with the same bedroom,

kitchen, and living-room configuration, but some have a fireplace or full base-
ment while others do not, or an attached garage instead of a carport.
It’s likely that the housing developer commissioned a master architect to cre-
ate a single blueprint to establish the basic design of all houses in the develop-
ment, then a series of new blueprints that include variations designed to appeal
to different buyers. The act of creating the series of blueprints was simplified since
they all begin with the same underlying structure, while the variations give them
unique characteristics that may be important to the prospective owners.
Creating a new blueprint that is based on an existing blueprint is analogous to
the object-oriented concept of inheritance, which is a powerful software develop-
ment technique and a defining characteristic of object-oriented programming.
derived classes
Inheritance is the process in which a new class is derived from an exist-
ing one. The new class automatically contains some or all of the vari-
ables and methods in the original class. Then, to tailor the class as
needed, the programmer can add new variables and methods to the
derived class or modify the inherited ones.
In general, new classes can be created via inheritance faster, easier,
and cheaper than by writing them from scratch. At the heart of inheritance is the
idea of software reuse. By using existing software components to create new ones,
we capitalize on the effort that went into the design, implementation, and testing
of the existing software.
Inheritance is the process of
deriving a new class from an
existing one.
key
concept
7.0 creating subclasses 383
Keep in mind that the word class comes from the idea of classifying
groups of objects with similar characteristics. Classification schemes

often use levels of classes that relate to each other. For example, all
mammals share certain characteristics: They are warmblooded, have
hair, and bear live offspring. Now consider a subset of mammals, such as horses.
All horses are mammals and have all of the characteristics of mammals, but they
also have unique features that make them different from other mammals.
If we translate this idea into software terms, an existing class called Mammal
would have certain variables and methods that describe the state and behavior of
mammals. A Horse class could be derived from the existing Mammal class,
automatically inheriting the variables and methods contained in
Mammal. The Horse class can refer to the inherited variables and meth-
ods as if they had been declared locally in that class. New variables and
methods can then be added to the derived class to distinguish a horse
from other mammals. Inheritance thus nicely models many situations
found in the natural world.
The original class that is used to derive a new one is called the parent class,
superclass, or base class. The derived class is called a child class, or subclass. Java
uses the reserved word extends to indicate that a new class is being derived from
an existing class.
The derivation process should establish a specific kind of relation-
ship between two classes: an is-a relationship. This type of relationship
means that the derived class should be a more specific version of the
original. For example, a horse is a mammal. Not all mammals are
horses, but all horses are mammals.
Let’s look at an example. The program shown in Listing 7.1 instantiates an
object of class
Dictionary, which is derived from a class called Book. In the main
method, two methods are invoked through the Dictionary object: one that was
declared locally in the
Dictionary class and one that was inherited from the
Book class.

The
Book class (see Listing 7.2) is used to derive the Dictionary class (see
Listing 7.3) using the reserved word extends in the header of Dictionary. The
Dictionary class automatically inherits the definition of the pageMessage
method and the pages variable. It is as if the pageMessage method and the
pages variable were declared inside the Dictionary class. Note that the
definitionMessage method refers explicitly to the pages variable.
One purpose of inheritance is
to reuse existing software.
key
concept
Inherited variables and meth-
ods can be used in the derived
class as if they had been
declared locally.
key
concept
Inheritance creates an is-a rela-
tionship between all parent and
child classes.
key
concept
384 CHAPTER 7 inheritance
Also, note that although the Book class is needed to create the definition of
Dictionary, no Book object is ever instantiated in the program. An instance of
a child class does not rely on an instance of the parent class.
Inheritance is a one-way street. The Book class cannot use variables or meth-
ods that are declared explicitly in the Dictionary class. For instance, if we cre-
ated an object from the Book class, it could not be used to invoke the
definitionMessage method. This restriction makes sense because a child class

is a more specific version of the parent class. A dictionary has pages because all
books have pages; but although a dictionary has definitions, not all books do.
Inheritance relationships are often represented in UML class diagrams. Figure
7.1 shows the inheritance relationship between the
Book and Dictionary classes.
An arrow with an open arrowhead is used to show inheritance in a UML dia-
gram, with the arrow pointing from the child class to the parent class.
listing
7.1
//********************************************************************
// Words.java Author: Lewis/Loftus
//
// Demonstrates the use of an inherited method.
//********************************************************************
public class Words
{
//
// Instantiates a derived class and invokes its inherited and
// local methods.
//
public static void main (String[] args)
{
Dictionary webster = new Dictionary ();
webster.pageMessage();
webster.definitionMessage();
}
}
Number of pages: 1500
Number of definitions: 52500
Definitions per page: 35

output
7.0 creating subclasses 385
the protected modifier
Not all variables and methods are inherited in a derivation. The visibility modi-
fiers used to declare the members of a class determine which ones are inherited
and which ones are not. Specifically, the child class inherits variables and meth-
ods that are declared public and does not inherit those that are declared private.
The pageMessage method is inherited by Dictionary because it is declared with
public visibility.
However, if we declare a variable with public visibility so that a
derived class can inherit it, we violate the principle of encapsulation.
Therefore, Java provides a third visibility modifier: protected. Note
that the variable
pages is declared with protected visibility in the Book
class. When a variable or method is declared with protected visibility,
a derived class will inherit it, retaining some of its encapsulation prop-
erties. The encapsulation with protected visibility is not as tight as it
would be if the variable or method were declared private, but it is better than if
it were declared public. Specifically, a variable or method declared with protected
listing
7.2
//********************************************************************
// Book.java Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a derived class to
// demonstrate inheritance.
//********************************************************************
public class Book
{
protected int pages = 1500;

//
// Prints a message about the pages of this book.
//
public void pageMessage ()
{
System.out.println ("Number of pages: " + pages);
}
}
Visibility modifiers determine
which variables and methods
are inherited. Protected visibil-
ity provides the best possible
encapsulation that permits
inheritance.
key
concept
386 CHAPTER 7 inheritance
listing
7.3
//********************************************************************
// Dictionary.java Author: Lewis/Loftus
//
// Represents a dictionary, which is a book. Used to demonstrate
// inheritance.
//********************************************************************
public class Dictionary extends Book
{
private int definitions = 52500;
//
// Prints a message using both local and inherited values.

//
public void definitionMessage ()
{
System.out.println ("Number of definitions: " + definitions);
System.out.println ("Definitions per page: " + definitions/pages);
}
}
figure 7.1 A UML class diagram showing an inheritance relationship
+ main (args : String[]) : void
Words
+ definitionMessage() : void
– definition : int
Dictionary
+ pageMessage() : void
# pages : int
Book
7.0 creating subclasses 387
visibility may be accessed by any class in the same package. The relationships
among all Java modifiers are explained completely in Appendix F.
In a UML diagram, protected visibility can be indicated by proceeding the pro-
tected member with a hash mark (#). The pages variable of the Book class has
this annotation in Fig. 7.1.
Each inherited variable or method retains the effect of its original visibility
modifier. For example, the pageMessage method is still considered to be public
in its inherited form.
Constructors are not inherited in a derived class, even though they have pub-
lic visibility. This is an exception to the rule about public members being inher-
ited. Constructors are special methods that are used to set up a particular type of
object, so it wouldn’t make sense for a class called Dictionary to have a con-
structor called Book.

the super reference
The reserved word super can be used in a class to refer to its parent class. Using
the super reference, we can access a parent’s members, even if they aren’t inher-
ited. Like the this reference, what the word super refers to depends on the class
in which it is used. However, unlike the this reference, which refers to a partic-
ular instance of a class, super is a general reference to the members of the par-
ent class.
One use of the super reference is to invoke a parent’s constructor.
Let’s look at an example. Listing 7.4 shows a modification of the orig-
inal Words program shown in Listing 7.1. Similar to the original ver-
sion, we use a class called Book2 (see Listing 7.5) as the parent of the
derived class
Dictionary2 (see Listing 7.6). However, unlike earlier
versions of these classes,
Book2 and Dictionary2 have explicit constructors used
to initialize their instance variables. The output of the
Words2 program is the
same as it is for the original Words program.
The
Dictionary2 constructor takes two integer values as parameters, repre-
senting the number of pages and definitions in the book. Because the Book2 class
already has a constructor that performs the work to set up the parts of the dictio-
nary that were inherited, we rely on that constructor to do that work. However,
since the constructor is not inherited, we cannot invoke it directly, and so we use
the super reference to get to it in the parent class. The Dictionary2 constructor
then proceeds to initialize its definitions variable.
A parent’s constructor can be
invoked using the
super
reference.

key
concept
388 CHAPTER 7 inheritance
In this case, it would have been just as easy to set the pages variable explicitly
in the Dictionary2 constructor instead of using super to call the Book2 con-
structor. However, it is good practice to let each class “take care” of itself. If we
choose to change the way that the Book2 constructor sets up its pages variable,
we would also have to remember to make that change in Dictionary2. By using
the
super reference, a change made in Book2 is automatically reflected in
Dictionary2.
A child’s constructor is responsible for calling its parent’s constructor. Gener-
ally, the first line of a constructor should use the
super reference call to a con-
structor of the parent class. If no such call exists, Java will automatically make a
call to super() at the beginning of the constructor. This rule ensures that a par-
ent class initializes its variables before the child class constructor begins to exe-
cute. Using the
super reference to invoke a parent’s constructor can be done in
listing
7.4
//********************************************************************
// Words2.java Author: Lewis/Loftus
//
// Demonstrates the use of the super reference.
//********************************************************************
public class Words2
{
//
// Instantiates a derived class and invokes its inherited and

// local methods.
//
public static void main (String[] args)
{
Dictionary2 webster = new Dictionary2 (1500, 52500);
webster.pageMessage();
webster.definitionMessage();
}
}
Number of pages: 1500
Number of definitions: 52500
Definitions per page: 35
output
7.0 creating subclasses 389
only the child’s constructor, and if included it must be the first line of the
constructor.
The super reference can also be used to reference other variables and methods
defined in the parent’s class. We discuss this technique later in this chapter.
multiple inheritance
Java’s approach to inheritance is called single inheritance. This term means that
a derived class can have only one parent. Some object-oriented languages allow
a child class to have multiple parents. This approach is called multiple inheri-
tance and is occasionally useful for describing objects that are in between two
listing
7.5
//********************************************************************
// Book2.java Author: Lewis/Loftus
//
// Represents a book. Used as the parent of a dervied class to
// demonstrate inheritance and the use of the super reference.

//********************************************************************
public class Book2
{
protected int pages;
//
// Sets up the book with the specified number of pages.
//
public Book2 (int numPages)
{
pages = numPages;
}
//
// Prints a message about the pages of this book.
//
public void pageMessage ()
{
System.out.println ("Number of pages: " + pages);
}
}
390 CHAPTER 7 inheritance
categories or classes. For example, suppose we had a class Car and a class Truck
and we wanted to create a new class called PickupTruck. A pickup truck is
somewhat like a car and somewhat like a truck. With single inheritance, we must
decide whether it is better to derive the new class from
Car or Truck. With mul-
tiple inheritance, it can be derived from both, as shown in Fig. 7.2.
listing
7.6
//********************************************************************
// Dictionary2.java Author: Lewis/Loftus

//
// Represents a dictionary, which is a book. Used to demonstrate
// the use of the super reference.
//********************************************************************
public class Dictionary2 extends Book2
{
private int definitions;
//
// Sets up the dictionary with the specified number of pages
// (maintained by the Book parent class) and defintions.
//
public Dictionary2 (int numPages, int numDefinitions)
{
super (numPages);
definitions = numDefinitions;
}
//
// Prints a message using both local and inherited values.
//
public void definitionMessage ()
{
System.out.println ("Number of definitions: " + definitions);
System.out.println ("Definitions per page: " + definitions/pages);
}
}

×