Sei sulla pagina 1di 28

Chapter 7: Inheritance

Solutions
Multiple Choice
Solutions
1. d
2. b
3. c
4. a
5. e
6. b
7. c
8. c
9. b
10. e

True/False
Solutions
1. F
2. T
3. F
4. F
5. F
6. T
7. T
8. T
9. T
10. F

Short Answer Solutions


7.1.

Draw an inheritance hierarchy containing classes that represent different types of clocks. Show the variables
and method names for two of these classes.
Clocks (display type, power or winding mechanism, time adjustment / reset
mechanism, size, color, digital or analog, case material)
Personal / Home
Worn
Wrist watches (Gender: mens, womens, unisex; band material)
Everyday
Dress
Sport
Pocket watches (with / without face covers, with / without
chain)
Belt watches
Pendant watches (necklace material and color)
Not Worn
Home clocks (illuminated, nonilluminated)
Nightstand clocks
Shelf Clocks
Desk clock
Wall clock (interior, exterior)
Vehicle clocks
Business
Interior
Desk
Wall
TimeCard
Exterior
Component
Appliance clocks (appliance type)
System clocks (system type: watering, lighting, security, computer)

7.2.

Show an alternative diagram for the hierarchy in the previous problem. Explain why it may be a better or
worse approach than the original.
Clocks (display type, power or winding mechanism, time adjustment / reset mechanism,
size, color, digital or analog, case material)
Attached, Built In, or Semi-permanent
Personal / Home
Wall clock (interior, exterior)
Vehicle clock

2007 Pearson Education

S 150

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

S 151

Business
Interior
Wall
TimeCard
Exterior
Component
Appliance clocks (appliance type)
System clocks (system type: watering, lighting, security, computer)
Independent
Personal / Home
Worn
Wrist watches (Gender: mens, womens, unisex; band material)
Everyday
Dress
Sport
Pocket watches (with / without face covers, with, without
chain)
Belt watches
Pendant watches (necklace material and color)
Not Worn
Home clocks (illuminated, nonilluminated)
Nightstand clocks
Shelf Clocks
Desk clock
Business
Desk
This could be a better approach because, typically, an attached, built-in, or semi-permanent clock is intended for group use
and, hence, may be the result of a group decision or a purchase for a group. An independent clock is typically intended for
individual use and, hence, may be the result of an individual decision or purchase by or for an individual. On the other
hand, the class diagram for the previous problem may be more suitable for a company which supplies all kinds of clocks
where the categories of users are more important than group vs. individual use.

7.3.

Draw a class hierarchy for types of teachers at a high school. Show what characteristics would be represented
in the various classes of the hierarchy. Explain how polymorphism could play a role in the process of
assigning courses to each teacher.
Teacher (name; salary; certifications)
FullTime (classroom)
PartTime (hours per week)
TeachingAssitant
StudentTeacher (university; cooperating teacher)
Polymorphism comes into play when a method on the Teacher class is used to assign
classes to teacher, but the implementation used for the method depends on which
kind of Teacher (FullTime, PartTime, TeachingAssistant, or StudentTeacher) the
Teacher actually is.

7.4.

Experiment with a simple derivation relationship between two classes. Put println statements in
constructors of both the parent and child classes. Do not explicitly call the constructor of the parent in the
child. What happens? Why? Change the childs constructor to explicitly call the constructor of the parent.
Now what happens?
Even in the absence of an explicit call
constructor is called when an object of
its program statements to be executed.
parents constructor causes its program
correct?)

7.5.

to the parents constructor, the parents


the child class is instantiated, causing
Similarly, an explicit call to the
statements to be executed. (Lar is this

What would happen if the pay method were not defined as an abstract method in the StaffMember class of
the Firm program (Listing 7.20)?
The pay method is the only abstract member of the StaffMember class,. If it were
not defined as abstract, there would be no abstract members in the StaffMember
class and, except for the abstract declaration in abstract public class
StaffMember it would be possible to instantiate objects of class StaffMember.

2007 Pearson Education

S 152

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

Further, classes which extend StaffMember would not have to provide their own pay
methods, defaulting instead to a pay method with a potentially empty definition.

7.6.

What would happen if, in the Dots program (Listing 7.28), we did not provide empty definitions for one or
more of the unused mouse events?
The compiler would complain because class DotsListener which implements
MouseListener must provide empty definitions for unused event methods.

7.7.

What would happen if the call to super.paintComponent were removed from the paintComponent
method of the DotsPanel class? Remove it and run the program to test your answer.
The paintComponent method is a member of class DotsPanel which extents JPanel
which means that the call to super.paintComponent is a call to the paintComponent
method of the JPanel class.
Without this call, the paintComponent method of the
JPanel class is not called. As a consequence, the panel is not painted, so the
black background is never painted, and any painting in the paintComponent method
paints over what was already there (which you can see as the count is updated).

Programming Project Solutions


7.1 Coin
//********************************************************************
// Coin.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.1
//
// Represents a coin with two sides that can be flipped.
//********************************************************************
public class Coin
{
public final int HEADS = 0;
public final int TAILS = 1;
private int face;
//----------------------------------------------------------------// Sets up the coin by flipping it initially.
//----------------------------------------------------------------public Coin ()
{
flip();
}
//----------------------------------------------------------------// Flips the coin by randomly choosing a face.
//----------------------------------------------------------------public void flip ()
{
face = (int) (Math.random() * 2);
}
//----------------------------------------------------------------// Returns the current face of the coin as an integer.
//----------------------------------------------------------------public int getFace ()
{
return face;
}
//----------------------------------------------------------------// Returns the current face of the coin as a string.
//---------------------------------------------------------------- 2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

public String toString()


{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
}
7.1 MonetaryCoin
//********************************************************************
// MonetaryCoin.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.1
//********************************************************************
public class MonetaryCoin extends Coin
{
private int value;
//----------------------------------------------------------------// Sets up a coin with a value.
//----------------------------------------------------------------public MonetaryCoin (int money)
{
super();
value = money;
}
//----------------------------------------------------------------// Sets the value of the coin.
//----------------------------------------------------------------public void setValue (int money)
{
value = money;
}
//----------------------------------------------------------------// Returns the current value of the coin.
//----------------------------------------------------------------public int getValue ()
{
return value;
}
//----------------------------------------------------------------// Returns a description of this coin as a string.
//----------------------------------------------------------------public String toString()
{
String result = super.toString();
result += "\t" + value;
return result;
}
}
7.1 MonetaryCoinDriver
//********************************************************************
// MonetaryCoinDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.1
2007 Pearson Education

S 153

S 154

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//********************************************************************
public class MonetaryCoinDriver
{
//----------------------------------------------------------------// Demonstrates the use of a MonetaryCoin as derived from Coin.
//----------------------------------------------------------------public static void main (String[] args)
{
MonetaryCoin[] coins = new MonetaryCoin[7];
coins[0]
coins[1]
coins[2]
coins[3]
coins[4]
coins[5]
coins[6]

=
=
=
=
=
=
=

new
new
new
new
new
new
new

MonetaryCoin(1);
MonetaryCoin(5);
MonetaryCoin(10);
MonetaryCoin(25);
MonetaryCoin(50);
MonetaryCoin(100);
MonetaryCoin(100);

// flip all of the coins


for (int flipping = 0; flipping < coins.length; flipping++)
coins[flipping].flip();
// compute total value
int sum = 0;
for (int adding = 0; adding < coins.length; adding++)
sum += coins[adding].getValue();
// print the coins
for (int index = 0; index < coins.length; index++)
System.out.println (coins[index]);
System.out.println ("\nTotal Value: " + sum);
}
}
7.2 Hospital
//********************************************************************
// Hospital.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Hospital
{
//----------------------------------------------------------------// Creates several objects from classes derived from
// HospitalEmployee.
//----------------------------------------------------------------public static void main (String [] args)
{
HospitalEmployee vito = new HospitalEmployee ("Vito", 123);
Doctor michael = new Doctor ("Michael", 234, "Heart");
Surgeon vincent = new Surgeon ("Vincent", 645, "Brain", true);
Nurse sonny = new Nurse ("Sonny", 789, 6);
Administrator luca = new Administrator ("Luca", 375, "Business");
Receptionist tom = new Receptionist ("Tom", 951, "Talking", true);
Janitor anthony = new Janitor ("Anthony", 123, "Maintenence", false);
// print the employees
System.out.println (vito);
System.out.println (michael);
System.out.println (vincent);
System.out.println (sonny);
System.out.println (luca);
System.out.println (tom);
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

System.out.println (anthony);
// invoke the specific methods of the objects
vito.work();
michael.diagnose();
vincent.operate();
sonny.assist();
luca.administrate();
tom.answer();
anthony.sweep();
}
}
7.2 Hospital Emplyee
//********************************************************************
// HospitalEmployee.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class HospitalEmployee
{
protected String name;
protected int number;
//----------------------------------------------------------------// Sets up this hospital employee with the specified information.
//----------------------------------------------------------------public HospitalEmployee (String empName, int empNumber)
{
name = empName;
number = empNumber;
}
//----------------------------------------------------------------// Sets the name for this employee.
//----------------------------------------------------------------public void setName (String empName)
{
name = empName;
}
//----------------------------------------------------------------// Sets the employee number for this employee.
//----------------------------------------------------------------public void setNumber (int empNumber)
{
number = empNumber;
}
//----------------------------------------------------------------// Returns this employee's name.
//----------------------------------------------------------------public String getName()
{
return name;
}
//----------------------------------------------------------------// Returns this employee's number.
//----------------------------------------------------------------public int getNumber()
{
return number;
}
2007 Pearson Education

S 155

S 156

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//----------------------------------------------------------------// Returns a description of this employee as a string.


//----------------------------------------------------------------public String toString()
{
return name + "\t" + number;
}
//----------------------------------------------------------------// Prints a message appropriate for this employee.
//----------------------------------------------------------------public void work()
{
System.out.println (name + " works for the hospital.");
}
}
7.2 Doctor
//********************************************************************
// Doctor.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Doctor extends HospitalEmployee
{
protected String specialty;
//----------------------------------------------------------------// Sets up this doctor with the specified information.
//----------------------------------------------------------------public Doctor (String empName, int empNumber, String special)
{
super (empName, empNumber);
specialty = special;
}
//----------------------------------------------------------------// Sets this doctor's specialty.
//----------------------------------------------------------------public void setSpecialty (String special)
{
specialty = special;
}
//----------------------------------------------------------------// Returns this doctor's specialty.
//----------------------------------------------------------------public String getSpecialty()
{
return specialty;
}
//----------------------------------------------------------------// Returns a description of this doctor as a string.
//----------------------------------------------------------------public String toString()
{
return super.toString() + "\t" + specialty;
}
//----------------------------------------------------------------// Prints a message appropriate for this doctor.
//----------------------------------------------------------------public void diagnose()
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

System.out.println (name + " is a(n) " + specialty + " doctor.");


}
}
7.2 Surgeon
//********************************************************************
// Surgeon.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Surgeon extends Doctor
{
protected boolean operating;
//----------------------------------------------------------------// Sets up this surgeon with the specified information.
//----------------------------------------------------------------public Surgeon (String empName, int empNumber,
String special, boolean isOper)
{
super (empName, empNumber, special);
operating = isOper;
}
//----------------------------------------------------------------// Sets the operating status of this surgeon.
//----------------------------------------------------------------public void setIsOperating (boolean isOper)
{
operating = isOper;
}
//----------------------------------------------------------------// Gets the current operating status of this surgeon.
//----------------------------------------------------------------public boolean getIsOperating()
{
return operating;
}
//----------------------------------------------------------------// Returns a description of this surgeon as a string.
//----------------------------------------------------------------public String toString()
{
return super.toString() + "\tOperating: " + operating;
}
//----------------------------------------------------------------// Prints a message appropriate for this surgeon.
//----------------------------------------------------------------public void operate()
{
System.out.print (name + " is");
if (!operating)
System.out.print (" not");
System.out.println (" operating now.");
}
}
7.2 Nurse
//********************************************************************
// Nurse.java
Authors: Lewis/Loftus/Cocking
//
2007 Pearson Education

S 157

S 158

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

// Solution to Programming Project 7.2


//********************************************************************
public class Nurse extends HospitalEmployee
{
protected int numPatients;
//----------------------------------------------------------------// Sets up this nurse with the information specified.
//----------------------------------------------------------------public Nurse (String empName, int empNumber, int numPat)
{
super (empName, empNumber);
numPatients = numPat;
}
//----------------------------------------------------------------// Sets the number of patients for this nurse.
//----------------------------------------------------------------public void setNumPatients (int pat)
{
numPatients = pat;
}
//----------------------------------------------------------------// Returns this nurse's current number of patients.
//----------------------------------------------------------------public int getNumPatients()
{
return numPatients;
}
//----------------------------------------------------------------// Returns a description of this nurse as a string.
//----------------------------------------------------------------public String toString()
{
return super.toString() + " has " + numPatients + " patients.";
}
//----------------------------------------------------------------// Prints a message appropriate for this nurse.
//----------------------------------------------------------------public void assist()
{
System.out.println (name + " is a nurse with " +
numPatients + " patients.");
}
}
7.2 Administrator
//********************************************************************
// Administrator.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Administrator extends HospitalEmployee
{
protected String department;
//----------------------------------------------------------------// Sets up this administrator with the specified information.
//----------------------------------------------------------------public Administrator (String empName, int empNumber, String dept)
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

super (empName, empNumber);


department = dept;
}
//----------------------------------------------------------------// Sets this administrator's department.
//----------------------------------------------------------------public void setDepartment (String dept)
{
department = dept;
}
//----------------------------------------------------------------// Returns this administrator's department.
//----------------------------------------------------------------public String getDepartment()
{
return department;
}
//----------------------------------------------------------------// Returns a description of this administrator as a string.
//----------------------------------------------------------------public String toString()
{
return super.toString() + " works in " + department;
}
//----------------------------------------------------------------// Prints a message appropriate for this administrator.
//----------------------------------------------------------------public void administrate()
{
System.out.println (name + " works in the " +
department + " department.");
}
}
7.2 Janitor
//********************************************************************
// Janitor.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Janitor extends Administrator
{
protected boolean sweeping;
//----------------------------------------------------------------// Sets up this janitor with the specified information.
//----------------------------------------------------------------public Janitor (String ename, int enum, String dept, boolean sw)
{
super (ename, enum, dept);
sweeping = sw;
}
//----------------------------------------------------------------// Sets the sweeping status of this janitor.
//----------------------------------------------------------------public void setIsSweeping (boolean isS)
{
sweeping = isS;
}
2007 Pearson Education

S 159

S 160

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//----------------------------------------------------------------// Returns the current sweeping status of this janitor.


//----------------------------------------------------------------public boolean getIsSweeping ()
{
return sweeping;
}
//----------------------------------------------------------------// Returns a description of this janitor as a string.
//----------------------------------------------------------------public String toString ()
{
return super.toString() + "\tSweeping: " + sweeping;
}
//----------------------------------------------------------------// Prints a message appropriate for this janitor.
//----------------------------------------------------------------public void sweep()
{
System.out.print (name + " is");
if (!sweeping)
System.out.print (" not");
System.out.println (" sweeping the floor.");
}
}
7.2 Receptionist
//********************************************************************
// Receptionist.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.2
//********************************************************************
public class Receptionist extends Administrator
{
protected boolean answering;
//----------------------------------------------------------------// Sets up this receptionist with the specified information.
//----------------------------------------------------------------public Receptionist (String ename, int enum, String dept,
boolean ans)
{
super (ename, enum, dept);
answering = ans;
}
//----------------------------------------------------------------// Sets the current answering status of this receptionist.
//----------------------------------------------------------------public void setIsAnswering (boolean isA)
{
answering = isA;
}
//----------------------------------------------------------------// Returns the current answering status of this receptionist.
//----------------------------------------------------------------public boolean getIsAnswering()
{
return answering;
}
//---------------------------------------------------------------- 2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

// Returns a description of this receptionist as a string.


//----------------------------------------------------------------public String toString()
{
return super.toString() + "\tAnswering: " + answering;
}
//----------------------------------------------------------------// Prints a message appropriate for this receptionist.
//----------------------------------------------------------------public void answer()
{
System.out.print (name + " is");
if (!answering)
System.out.print (" not");
System.out.println (" answering the phone.");
}
}
7.3 BookClub
//********************************************************************
// BookClub.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
public class BookClub
{
//----------------------------------------------------------------// Creates several objects from classes derived from the
// ReadingMatter class.
//----------------------------------------------------------------public static void main (String[] args)
{
ReadingMatter[] rm = new ReadingMatter[5];
rm[0] = new ReadingMatter ("Myst Strategy", "0-7615-0807-4");
rm[1] = new Book ("Great Eskimo Vocabulary Hoax, The",
"0-226-68534-9",
"Pullum, Geoffrey");
rm[2] = new TextBook ("Java Software Solutions",
"0-201-61271-2",
"Lewis, John and William Loftus",
true);
String[] names = { "Hazel", "Fiver", "Bigwig",
"Blackberry", "Dandelion" };
rm[3] = new Novel ("Watership Down",
"0-380-00293-0",
"Adams, Richard", names);
rm[4] = new Magazine ("ACM Crossroads",
"0-234-5678-0",
"Perry, Lynellen and others");
for (int index = 0; index < rm.length; index++)
{
rm[index].content();
System.out.println();
}
}
}
2007 Pearson Education

S 161

S 162

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

7.3 Reading Matter


//********************************************************************
// ReadingMatter.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
public class ReadingMatter
{
protected String title, isbn;
//----------------------------------------------------------------// Sets up this reading matter with the specified information.
//----------------------------------------------------------------public ReadingMatter (String thisTitle, String isbnNum)
{
title = thisTitle;
isbn = isbnNum;
}
//----------------------------------------------------------------// Sets the title for this reading matter.
//----------------------------------------------------------------public void setTitle (String thisTitle)
{
title = thisTitle;
}
//----------------------------------------------------------------// Sets the isbn number for this reading matter.
//----------------------------------------------------------------public void setISBN (String isbnNum)
{
isbn = isbnNum;
}
//----------------------------------------------------------------// Returns the title of this reading matter.
//----------------------------------------------------------------public String getTitle()
{
return title;
}
//----------------------------------------------------------------// Returns the isbn number of this reading matter.
//----------------------------------------------------------------public String getISBN()
{
return isbn;
}
//----------------------------------------------------------------// Returns a description of this reading matter as a string.
//----------------------------------------------------------------public String toString()
{
return (title + "\t" + isbn);
}
//----------------------------------------------------------------// Prints a message appropriate for this reading matter.
//----------------------------------------------------------------public void content()
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

System.out.println ("Title: " + title);


System.out.println ("ISBN: " + isbn);
}
}
7.3 Book
//********************************************************************
// Book.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
public class Book extends ReadingMatter
{
protected String author;
//----------------------------------------------------------------// Sets up this book with the specified information.
//----------------------------------------------------------------public Book (String thisTitle, String isbnNum, String auth)
{
super (thisTitle, isbnNum);
author = auth;
}
//----------------------------------------------------------------// Sets the author for this book.
//----------------------------------------------------------------public void setAuthor (String auth)
{
author = auth;
}
//----------------------------------------------------------------// Returns the author of this book.
//----------------------------------------------------------------public String getAuthor()
{
return author;
}
//----------------------------------------------------------------// Returns a description of this book as a string.
//----------------------------------------------------------------public String toString()
{
return super.toString() + "\t" + author;
}
//----------------------------------------------------------------// Prints a message appropriate for this book.
//----------------------------------------------------------------public void content()
{
super.content();
System.out.println ("Author: " + author);
}
}
7.3 Novel
//********************************************************************
// Novel.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
2007 Pearson Education

S 163

S 164

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

public class Novel extends Book


{
protected String[] characters;
//----------------------------------------------------------------// Sets up this novel with the specified information.
//----------------------------------------------------------------public Novel (String thisTitle, String isbnNum, String auth,
String[] chars)
{
super (thisTitle, isbnNum, auth);
characters = chars;
}
//----------------------------------------------------------------// Sets the cast of characters for this novel.
//----------------------------------------------------------------public void setCharacters (String[] chars)
{
characters = chars;
}
//----------------------------------------------------------------// Returns the cast of characters for this novel.
//----------------------------------------------------------------public String[] getCharacters()
{
return characters;
}
//----------------------------------------------------------------// Returns a description of this novel as a string.
//----------------------------------------------------------------public String toString()
{
String result = super.toString();
for (int index = 0; index < characters.length; index++)
result += "\n" + characters[index];
return result;
}
//----------------------------------------------------------------// Prints a message appropriate for this novel.
//----------------------------------------------------------------public void content()
{
super.content();
for (int index = 0; index < characters.length; index++)
System.out.println (characters[index]);
}
}
7.3 TextBook
//********************************************************************
// TextBook.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
public class TextBook extends Book
{
protected boolean answers;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//----------------------------------------------------------------// Sets up this textbook with the specified information.


//----------------------------------------------------------------public TextBook (String thisTitle, String isbnNum, String auth,
boolean ans)
{
super (thisTitle, isbnNum, auth);
answers = ans;
}
//----------------------------------------------------------------// Sets whether the answers are provided for this textbook.
//----------------------------------------------------------------public void setAnswers (boolean ans)
{
answers = ans;
}
//----------------------------------------------------------------// Returns whether the answers are provided for this textbook.
//----------------------------------------------------------------public boolean getAnswers()
{
return answers;
}
//----------------------------------------------------------------// Returns a description of this textbook as a string.
//----------------------------------------------------------------public String toString ()
{
String result = super.toString();
if (!answers)
result += "no ";
result += "answers given";
return result;
}
//----------------------------------------------------------------// Prints a message appropriate for this textbook.
//----------------------------------------------------------------public void content()
{
super.content();
System.out.println ("Answers provided: " + answers);
}
}
7.3 Magazine
//********************************************************************
// Magazine.java
Authors: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.3
//********************************************************************
public class Magazine extends ReadingMatter
{
protected String editor;
//----------------------------------------------------------------// Sets up this magazine with the specified information.
//----------------------------------------------------------------public Magazine (String thisTitle, String isbnNum, String ed)
{
super (thisTitle, isbnNum);
editor = ed;
2007 Pearson Education

S 165

S 166

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

}
//----------------------------------------------------------------// Sets the editor for this magazine.
//----------------------------------------------------------------public void setEditor (String ed)
{
editor = ed;
}
//----------------------------------------------------------------// Returns the editor for this magizine.
//----------------------------------------------------------------public String getEditor()
{
return editor;
}
//----------------------------------------------------------------// Returns a description of this magazine as a string.
//----------------------------------------------------------------public String toString()
{
String result = super.toString();
result += "\t" + editor;
return result;
}
//----------------------------------------------------------------// Prints a message appropriate for this magizine.
//----------------------------------------------------------------public void content()
{
super.content();
System.out.println ("Editor: " + editor);
}
}
7.4 Players
//********************************************************************
// Players.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.4
//********************************************************************
public class Players
{
//----------------------------------------------------------------// Exercises the sport statistic classes.
//----------------------------------------------------------------public static void main (String [] args)
{
BaseballStats player1;
FootballStats player2;
player1 = new BaseballStats ("Sal Runner", "Phillies");
player2 = new FootballStats ("Mel Rogers", "Redskins");
player1.score();
player2.score();
player1.getHit();
player2.gainYards(15);
System.out.println (player1);
System.out.println ();
System.out.println (player2);
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

}
}
7.4 PlayerStats
//********************************************************************
// PlayerStats.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.4
//********************************************************************
public abstract class PlayerStats
{
protected String player, team;
protected int score;
//----------------------------------------------------------------// Sets up this stat object with the specified info.
//----------------------------------------------------------------public PlayerStats (String playerName, String teamName)
{
player = playerName;
team = teamName;
score = 0;
}
//----------------------------------------------------------------// Returns the score.
//----------------------------------------------------------------public int getScore()
{
return score;
}
//----------------------------------------------------------------// Updates the score as appropriate depending on the sport.
//----------------------------------------------------------------public abstract void score();
//----------------------------------------------------------------// Returns a description of this stats object as a string.
//----------------------------------------------------------------public String toString()
{
String result = "Player: " + player;
result += "\nTeam: " + team;
result += "\nScore: " + score;
return result;
}
}
7.4 BaseballStats
//********************************************************************
// BaseballStats.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.4
//********************************************************************
public class BaseballStats extends PlayerStats
{
protected int hits, errors;
//----------------------------------------------------------------// Sets up this baseball stat object with the specified info.
//----------------------------------------------------------------public BaseballStats (String player, String team)
2007 Pearson Education

S 167

S 168

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

{
super (player, team);
hits = 0;
errors = 0;
}
//----------------------------------------------------------------// Increase the score by 1.
//----------------------------------------------------------------public void score()
{
score += 1;
}
//----------------------------------------------------------------// Increment the number of hits.
//----------------------------------------------------------------public void getHit()
{
hits += 1;
}
//----------------------------------------------------------------// Returns the current number of errors.
//----------------------------------------------------------------public void commitError()
{
errors += 1;
}
//----------------------------------------------------------------// Returns the current number of hits.
//----------------------------------------------------------------public int getHits()
{
return hits;
}
//----------------------------------------------------------------// Returns the current number of errors.
//----------------------------------------------------------------public int getErrors()
{
return errors;
}
//----------------------------------------------------------------// Returns a description of this stats object as a string.
//----------------------------------------------------------------public String toString()
{
String result = super.toString();
result += "\nHits: " + hits;
result += "\nErrors: " + errors;
return result;
}
}
7.4 FootbalStats
//********************************************************************
// FootballStats.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.4
//********************************************************************
public class FootballStats extends PlayerStats
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

{
protected int yards;
//----------------------------------------------------------------// Sets up this football stat object with the specified info.
//----------------------------------------------------------------public FootballStats (String player, String team)
{
super (player, team);
yards = 0;
}
//----------------------------------------------------------------// Increase the score by 6.
//----------------------------------------------------------------public void score()
{
score += 6;
}
//----------------------------------------------------------------// Update the number of yards gained.
//----------------------------------------------------------------public void gainYards (int numYards)
{
yards += numYards;
}
//----------------------------------------------------------------// Returns the current number of yards.
//----------------------------------------------------------------public int getYards()
{
return yards;
}
//----------------------------------------------------------------// Returns a description of this stats object as a string.
//----------------------------------------------------------------public String toString()
{
String result = super.toString();
result += "\nYards: " + yards;
return result;
}
}
7.5 Demographics
//********************************************************************
// Demographics.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.5
//********************************************************************
public class Demographics {
//-----------------------------------------------------------------// Driver for creating demographics
//-----------------------------------------------------------------public static void main(String args[])
{
Person[] demos = new Person[4];
demos[0] = new Person(8, "Utah");
demos[1] = new Student(25, "New Mexico", "University of New Mexico");
2007 Pearson Education

S 169

S 170

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

demos[2] = new ForeignStudent(19, "Ohio", "Ohio State", "India");


demos[3] = new Employee(38, "Delaware", "Tile Setter", 40000);
for (int i=0; i<demos.length; i++)
System.out.println(demos[i] + "\n---------------------\n");
}
}
7.5 Employee
//********************************************************************
// Employee.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.5
//********************************************************************
import java.text.NumberFormat;
public class Employee extends Person {
private String occupation;
private int income;
//-----------------------------------------------------------------// Creates an employee with age and location, occupation and income
//-----------------------------------------------------------------public Employee(int personAge, String personLocation,
String personOccupation, int personIncome)
{
super( personAge, personLocation);
occupation = personOccupation;
income = personIncome;
}
public String toString()
{
return super.toString() + "\nOccupation: " + occupation
+ "\nIncome: "
+ NumberFormat.getCurrencyInstance().format(income);
}
}
7.5 ForeignStudent
//********************************************************************
// ForeignStudent.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.5
//********************************************************************
public class ForeignStudent extends Student {
private String nationality;
//-----------------------------------------------------------------// Creates a student with age and location and university, and nationality
//-----------------------------------------------------------------public ForeignStudent(int personAge, String personLocation,
String personUniversity, String personNationality)
{
super(personAge, personLocation, personUniversity);
nationality = personNationality;
}
public String toString()
{
return super.toString() + "\nNationality: " + nationality;
}
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

S 171

}
7.5 Person
//********************************************************************
// Person.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.5
//********************************************************************
public class Person {
private int age;
private String location;
//-----------------------------------------------------------------// Creates a person with age and location
//-----------------------------------------------------------------public Person(int personAge, String personLocation)
{
age = personAge;
location = personLocation;
}
public String toString()
{
return "Age: " + age + "\nLocation: " + location;
}
}
7.5 Student
//********************************************************************
// Student.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.5
//********************************************************************
public class Student extends Person
{
private String university;
//-----------------------------------------------------------------// Creates a student with age and location and university
//-----------------------------------------------------------------public Student(int personAge, String personLocation, String personUniversity)
{
super(personAge, personLocation);
university = personUniversity;
}
public String toString()
{
return super.toString() + "\nUniversity: " + university;
}
}
7.6 TrafficLight
//********************************************************************
// TrafficLight.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.6
//********************************************************************
import javax.swing.*;
2007 Pearson Education

S 172

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

public class TrafficLight


{
//----------------------------------------------------------------// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame lightFrame = new JFrame ("Traffic Light");
lightFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
lightFrame.getContentPane().add (new TrafficControlPanel());
lightFrame.setSize(160,250);
lightFrame.show();
}
}
7.6 TrafficControlPanel
//********************************************************************
// TrafficControlPanel.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.6
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficControlPanel extends JPanel
{
TrafficLightPanel light;
public TrafficControlPanel()
{
setLayout(new BorderLayout());
light = new TrafficLightPanel();
add(light, BorderLayout.CENTER);
JButton change = new JButton("Change Light");
change.addActionListener(new ChangeListener());
add(change, BorderLayout.SOUTH);
}
class ChangeListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
light.change();
}
}
}
7.6 TrafficLightPanel
//********************************************************************
// TrafficLightPanel.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 7.6
//********************************************************************
import javax.swing.*;
import java.awt.*;
public class TrafficLightPanel extends JPanel
{
private int currentState = 0;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

S 173

private final int NUM_LIGHTS = 3;


private final int X = 50, Y = 10, WIDTH = 50, HEIGHT = 130;
private final int DIAMETER = 30;
private final int X_OFFSET = 10, Y_OFFSET = 10;
private final int PANEL_WIDTH = 150, PANEL_HEIGHT = 230;
//----------------------------------------------------------------// Creates the traffic light panel
//----------------------------------------------------------------public void TrafficLightPanel()
{
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
}
public Dimension getPreferredSize()
{
return new Dimension(PANEL_WIDTH, PANEL_HEIGHT);
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
int lightOn = currentState % NUM_LIGHTS;
setBackground(Color.white);
page.setColor(Color.lightGray);
page.fillRect(X, Y, WIDTH, HEIGHT);
if (lightOn == 0)
page.setColor(Color.red);
else
page.setColor(Color.darkGray);
page.fillOval(X+X_OFFSET, Y+Y_OFFSET, DIAMETER, DIAMETER);
if (lightOn == 1)
page.setColor(Color.yellow);
else
page.setColor(Color.darkGray);
page.fillOval(X+X_OFFSET, Y+DIAMETER+2*Y_OFFSET, DIAMETER, DIAMETER);
if (lightOn == 2)
page.setColor(Color.green);
else
page.setColor(Color.darkGray);
page.fillOval(X+X_OFFSET, Y+2*DIAMETER+3*Y_OFFSET, DIAMETER, DIAMETER);
}
public void change()
{
currentState++;
repaint();
}
}
7.7 RubberCircle
//********************************************************************
// RubberCircle.java
Author: Lewis/Loftus/Cocking/Alicia Nicoll
//
// Solution to Programming Project 7.7
//********************************************************************
import javax.swing.JApplet;
2007 Pearson Education

S 174

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

public class RubberCircle extends JApplet


{
public void init ()
{
getContentPane().add(new RubberCirclePanel());
}
}
7.7 RubberCirclePanel
//********************************************************************
// RubberCirclePanel.java
Author: Lewis/Loftus/Cocking/Alicia Nicoll
//
// Solution to Programming Project 7.7
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RubberCirclePanel extends JPanel
{
private Point center = null, current = null;
//----------------------------------------------------------------// Initializes the panel
//----------------------------------------------------------------public RubberCirclePanel ()
{
RubberCircleListener listener = new RubberCircleListener();
addMouseListener (listener);
addMouseMotionListener (listener);
setBackground (Color.black);
}
//----------------------------------------------------------------// Draws the current circle centered around an original point.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor (Color.red);
if (center != null && current != null)
{
int xDelta = center.x - current.x;
int yDelta = center.y - current.y;
double radius = Math.sqrt ( Math.pow(xDelta, 2) +
Math.pow(yDelta, 2) );
int
int
int
int

height = (int)(radius*2);
width = (int)(radius*2);
top = (int)(center.x - radius);
left = (int)(center.y - radius);

page.drawOval (top, left, width, height);


}
}
//*****************************************************************
// Represents a listener for all mouse events.
//*****************************************************************
private class RubberCircleListener implements MouseListener,
MouseMotionListener
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//-------------------------------------------------------------// Stores the point the mouse was at when it is first pressed.
//-------------------------------------------------------------public void mousePressed (MouseEvent event)
{
center = event.getPoint();
}
//-------------------------------------------------------------// Obtains the current mouse position and records it. And draws
// the circle to create the rubberband effect.
//-------------------------------------------------------------public void mouseDragged (MouseEvent event)
{
current = event.getPoint();
repaint();
}
//-------------------------------------------------------------// Empty definitions for the unused event methods.
//-------------------------------------------------------------public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved (MouseEvent event) {}
}
}
7.8 Odometer
//********************************************************************
// Odometer.java
Author: Lewis/Loftus/Cocking/Alicia Nicoll
//
// Solution to Programming Project 7.8
//********************************************************************
import javax.swing.JApplet;
public class Odometer extends JApplet
{
public void init ()
{
getContentPane().add(new OdometerPanel());
}
}
7.8 OdometerPanel
//********************************************************************
// OdometerPanel.java
Author: Lewis/Loftus/Cocking/Alicia Nicoll
//
// Solution to Programming Project 7.8
//********************************************************************
import
import
import
import

javax.swing.*;
java.awt.*;
java.awt.event.*;
java.text.DecimalFormat;

public class OdometerPanel extends JPanel


{
private final int APPLET_WIDTH = 300;
private final int APPLET_HEIGHT = 300;
private double totalDistance;
private Point current = null, previous = null;
2007 Pearson Education

S 175

S 176

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

private DecimalFormat fmt;


//----------------------------------------------------------------// Initializes the panel
//----------------------------------------------------------------public OdometerPanel ()
{
OdometerListener listener = new OdometerListener();
addMouseListener (listener);
addMouseMotionListener (listener);
totalDistance = 0.0;
fmt = new DecimalFormat ("0.#");
setBackground (Color.black);
}
//-----------------------------------------------------------------// Displays the distance the mouse has traveled.
//-----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor(Color.green);
String result = "Distance: " + fmt.format(totalDistance);
page.drawString (result, 100, 100);
}
//*****************************************************************
// Represents the listener for the mouse
//*****************************************************************
private class OdometerListener implements MouseListener,
MouseMotionListener
{
//-------------------------------------------------------------// Updates the odometer value based on the current position
// of the mouse.
//-------------------------------------------------------------public void mouseMoved (MouseEvent event)
{
current = event.getPoint();
if(current != null && previous != null)
{
int xDelta = current.x - previous.x;
int yDelta = current.y - previous.y;
double distance = Math.sqrt( Math.pow(xDelta, 2) +
Math.pow(yDelta, 2) );
totalDistance += distance;
}
previous = current;
repaint();
}
//-------------------------------------------------------------// Determines where the mouse entered the applet.
//-------------------------------------------------------------public void mouseEntered (MouseEvent event)
{
previous = event.getPoint();
}
//-----------------------------------------------------------------// Provides empty definitions for unused event methods.
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 7 Solutions

//-----------------------------------------------------------------public void mouseClicked (MouseEvent event) {}


public void mouseReleased (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mousePressed (MouseEvent event) {}
public void mouseDragged (MouseEvent event) {}
}
}
AP-Style Multiple Choice
Solutions
1. B
2. D
3. C
4. C
5. C
6. A

AP-Style Free Response Solution


7.1
a.
public class Perishable extends InventoryItem
{
private Date expiration;
private static final double DISCOUNT = 0.01;
public Perishable (Date entry, double price, Date expirationDate)
{
super (entry, price);
expiration = expirationDate;
}
public double getPrice()
{
if (expiration.compareTo(getEntryDate()) < 0)
return getBasePrice() * DISCOUNT;
else
return getBasePrice();
}
}

b.
public ArrayList<InventoryItem> getItems (double loPrice, double hiPrice)
{
ArrayList<InventoryItem> list = new ArrayList<InventoryItem>();
for (InventoryItem ii : items)
{
if ((ii.getPrice() >= loPrice) && (ii.getPrice() <= hiPrice))
list.add(ii);
}
return list;
}

2007 Pearson Education

S 177

Potrebbero piacerti anche