Documente Academic
Documente Profesional
Documente Cultură
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
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
S 150
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.
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.
S 152
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).
S 153
S 154
//********************************************************************
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);
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
S 157
S 158
S 159
S 160
S 161
S 162
S 163
S 164
S 165
S 166
}
//----------------------------------------------------------------// 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
}
}
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
{
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
{
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
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
S 173
S 174
height = (int)(radius*2);
width = (int)(radius*2);
top = (int)(center.x - radius);
left = (int)(center.y - radius);
//-------------------------------------------------------------// 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;
S 175
S 176
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;
}
S 177