Chapter 10: Polymorphism 173
Chapter 10: Polymorphism
Lab Exercises
Topics Lab Exercises
Polymorphism via Inheritance Another Type of Employee
Painting Shapes
Sorting & Searching Polymorphic Sorting
Searching and Sorting An Integer List
174 Chapter 10: Polymorphism
Another Type of Employee
The files Firm.java, Staff.java, StaffMember.java, Volunteer.java, Employee.java, Executive.java, and
Hourly.java are from Listings 9.1 – 9.7 in the text. The program illustrates inheritance and polymorphism.
In this exercise you will add one more employee type to the class hierarchy (see Figure 9.1 in the text).
The employee will be one that is an hourly employee but also earns a commission on sales. Hence the class,
which we’ll name Commission, will be derived from the Hourly class.
Write a class named Commission with the following features:
It extends the Hourly class.
It has two instance variables (in addition to those inherited): one is the total sales the employee has made
(type double) and the second is the commission rate for the employee (the commission rate will be type
double and will represent the percent (in decimal form) commission the employee earns on sales (so .2
would mean the employee earns 20% commission on sales)).
The constructor takes 6 parameters: the first 5 are the same as for Hourly (name, address, phone number,
social security number, hourly pay rate) and the 6th is the commission rate for the employee. The
constructor should call the constructor of the parent class with the first 5 parameters then use the 6th to set
the commission rate.
To test your class, update Staff.java as follows:
Increase the size of the array to 8.
Add two commissioned employees to the staffList—make up your own names, addresses, phone numbers
Compile and run the program. Make sure it is working properly.
//*****************************************************************
// Firm.java Author: Lewis/Loftus
public class Firm
{
//————————————————————–
personnel.payday();
}
}
Chapter 10: Polymorphism 175
//********************************************************************
// Staff.java Author: Lewis/Loftus
//
// Represents the personnel staff of a particular business.
//********************************************************************
public class Staff
{
staffList[1] = new Employee (“Carla”, “456 Off Line”,
“555-0101”, “987-65-4321”, 1246.15);
staffList[2] = new Employee (“Woody”, “789 Off Rocker”,
“555-0000”, “010-20-3040”, 1169.23);
((Hourly)staffList[3]).addHours (40);
}
//—————————————————————–
// Pays all staff members.
//—————————————————————–
public void payday ()
{
double amount;
for (int count=0; count < staffList.length; count++)
{
}
}
176 Chapter 10: Polymorphism
//******************************************************************
// StaffMember.java Author: Lewis/Loftus
//
// Represents a generic staff member.
//******************************************************************
abstract public class StaffMember
{
name = eName;
address = eAddress;
phone = ePhone;
}
//—————————————————————
// Returns a string including the basic employee information.
//—————————————————————
public String toString()
// employee.
//—————————————————————
public abstract double pay();
}
Chapter 10: Polymorphism 177
//******************************************************************
// Volunteer.java Author: Lewis/Loftus
//
//—————————————————————
public Volunteer (String eName, String eAddress, String ePhone)
{
super (eName, eAddress, ePhone);
}
}
178 Chapter 10: Polymorphism
//******************************************************************
// Employee.java Author: Lewis/Loftus
//—————————————————————
// Sets up an employee with the specified information.
//—————————————————————
public Employee (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
{
super (eName, eAddress, ePhone);
String result = super.toString ();
result += “\nSocial Security Number: ” + socialSecurityNumber;
return result;
}
}
Chapter 10: Polymorphism 179
//******************************************************************
private double bonus;
//—————————————————————–
// Sets up an executive with the specified information.
//—————————————————————–
public Executive (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
bonus = execBonus;
}
//—————————————————————–
// Computes and returns the pay for an executive, which is the
// regular employee payment plus a one-time bonus.
//—————————————————————–
public double pay()
{
double payment = super.pay() + bonus;
bonus = 0;
180 Chapter 10: Polymorphism
//******************************************************************
// Hourly.java Author: Lewis/Loftus
//—————————————————————–
// Sets up this hourly employee using the specified information.
//—————————————————————–
public Hourly (String eName, String eAddress, String ePhone,
String socSecNumber, double rate)
{
super (eName, eAddress, ePhone, socSecNumber, rate);
hoursWorked = 0;
}
//—————————————————————–
// Computes and returns the pay for this hourly employee.
//—————————————————————–
public double pay()
{
double payment = payRate * hoursWorked;
hoursWorked = 0;
return payment;
}
Painting Shapes
In this lab exercise you will develop a class hierarchy of shapes and write a program that computes the amount
of paint needed to paint different objects. The hierarchy will consist of a parent class Shape with three derived
classes – Sphere, Rectangle, and Cylinder. For the purposes of this exercise, the only attribute a shape will have
is a name and the method of interest will be one that computes the area of the shape (surface area in the case of
three-dimensional shapes). Do the following.
1. Write an abstract class Shape with the following properties:
2. The file Sphere.java contains a class for a sphere which is a descendant of Shape. A sphere has a radius
and its area (surface area) is given by the formula 4*PI*radius^2. Define similar classes for a rectangle
3. The file Paint.java contains a class for a type of paint (which has a “coverage” and a method to
compute the amount of paint needed to paint a shape). Correct the return statement in the amount
4. The file PaintThings.java contains a program that computes the amount of paint needed to paint
various shapes. A paint object has been instantiated. Add the following to complete the program:
Instantiate the three shape objects: deck to be a 20 by 35 foot rectangle, bigBall to be a sphere of
radius 15, and tank to be a cylinder of radius 10 and height 30.
Make the appropriate method calls to assign the correct values to the three amount variables.
Run the program and test it. You should see polymorphism in action as the amount method
computes the amount of paint for various shapes.
//*****************************************
// Sphere.java
//———————————-
// Constructor: Sets up the sphere.
//———————————-
public Sphere(double r)
{
super(“Sphere”);
radius = r;
}
//—————————————–
182 Chapter 10: Polymorphism
}
}
//*****************************************************
// Paint.java
//
// Represents a type of paint that has a fixed area
// covered by a gallon. All measurements are in feet.
// *****************************************************
//—————————————————
public double amount(Shape s)
{
System.out.println (“Computing amount for ” + s);
return 0;
}
}
Chapter 10: Polymorphism 183
// and prints the amount of paint needed
// to paint each shape.
//—————————————–
public static void main (String[] args)
{
final double COVERAGE = 350;
System.out.println (“Deck ” + fmt.format(deckAmt));
System.out.println (“Big Ball ” + fmt.format(ballAmt));
System.out.println (“Tank ” + fmt.format(tankAmt));
}
}
184 Chapter 10: Polymorphism
Polymorphic Sorting
1. The file Numbers.java reads in an array of integers, invokes the selection sort algorithm to sort them,
2. Try to compile Numbers.java and see what the error message is. The problem involves the difference between
4. Modify the insertionSort algorithm so that it sorts in descending order rather than ascending order.
5. The file Salesperson.java partially defines a class that represents a sales person. This is very similar to
the Contact class in Listing 9.10. However, a sales person has a first name, last name, and a total
6. The file WeeklyS ales .java contains a driver for testing the compareTo method and the sorting (this is
7. OPTIONAL: Modify WeeklySales.java so the salespeople are read in rather than hardcoded in the
program.
//******************************************************************
// Sorting.java Author: Lewis/Loftus
//
// Demonstrates the selection sort and insertion sort algorithms.
//******************************************************************
public class Sorting
{
//—————————————————————–
Chapter 10: Polymorphism 185
min = scan;
// Swap the values
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
{
list[position] = list[position-1];
position–;
}
list[position] = key;
}
}
}
//**********************************************************
//———————————————
public static void main (String[] args)
{
int[] intList;
int size;
Scanner scan = new Scanner(System.in);
System.out.print (“\nHow many integers do you want to sort? “);
size = scan.nextInt();
intList = new int[size];
186 Chapter 10: Polymorphism
System.out.println (“\nYour numbers in sorted order…”);
for (int i = 0; i < size; i++)
System.out.print(intList[i] + ” “);
System.out.println ();
}
}
// *******************************************************
// Salesperson.java
//——————————————————
// Constructor: Sets up the sales person object with
// the given data.
//——————————————————
public Salesperson (String first, String last, int sales)
{
firstName = first;
lastName = last;
totalSales = sales;
}
//——————————————-
// Returns the sales person as a string.
//——————————————-
public String toString()
{
return lastName + “, ” + firstName + “: \t” + totalSales;
}
//————————————————–
// Order is based on total sales with the name
// (last, then first) breaking a tie.
//————————————————–
public int compareTo(Object other)
{
int result;
return result;
}
Chapter 10: Polymorphism 187
return firstName;
}
//————————-
// Last name accessor.
//————————-
public String getLastName()
{
return lastName;
// ******************************************************************
// WeeklySales.java
//
// Sorts the sales staff in descending order by sales.
// ******************************************************************
public class WeeklySales
{
public static void main(String[] args)
{
Salesperson[] salesStaff = new Salesperson[10];
salesStaff[0] = new Salesperson(“Jane”, “Jones”, 3000);
salesStaff[1] = new Salesperson(“Daffy”, “Duck”, 4935);
salesStaff[2] = new Salesperson(“James”, “Jones”, 3000);
salesStaff[9] = new Salesperson(“Walt”, “Smith”, 3000);
Sorting.insertionSort(salesStaff);
System.out.println (“\nRanking of Sales for the Week\n”);
for (Salesperson s : salesStaff)
System.out.println (s);
}
}
Searching and Sorting In An Integer List
File IntegerList.java contains a Java class representing a list of integers. The following public methods are
provided:
IntegerList(int size)—creates a new list of size elements. Elements are initialized to 0.
File IntegerListTest.java contains a Java program that provides menu-driven testing for the IntegerList class.
Copy both files to your directory, and compile and run IntegerListTest to see how it works. For example, create
a list, print it, and search for an element in the list. Does it return the correct index? Now look for an element
1. Add a method void replaceFirst(int oldVal, int newVal) to the IntegerList class that replaces the first
occurrence of oldVal in the list with newVal. If oldVal does not appear in the list, it should do nothing (but
2. Add a method void replaceAll(int oldVal, int newVal) to the IntegerList class that replaces all occurrences
of oldVal in the list with newVal. If oldVal does not appear in the list, it should do nothing (but it’s not an
error). Does it still make sense to use the search method like you did for replaceFirst, or should you do
your own searching here? Think about this.
3. Add a method void sortDecreasing() to the IntegerList class that sorts the list into decreasing (instead of
4. Add a method int binarySearchD (int target) to the IntegerList class that uses a binary search to find the
target assuming the list is sorted in decreasing order. If the target is found, the method should return its
index; otherwise the method should return –1. Your algorithm will be a modification of the binary search
algorithm in listing 10.12 of the text.
Add an option to the menu in IntegerListTest to test your new method. In testing, make sure your method
Chapter 10: Polymorphism 189
public class IntegerLis0074
{
int[] list; //values in the list
//——————————————————-
//create a list of the given size
//——————————————————-
public IntegerList(int size)
{
list = new int[size];
}
{
for (int i=0; i<list.length; i++)
System.out.println(i + “:\t” + list[i]);
}
//——————————————————-
//return the index of the first occurrence of target in the list.
//return -1 if target does not appear in the list
//——————————————————-
public void selectionSort()
{
int minIndex;
for (int i=0; i < list.length-1; i++)
{
//find smallest element in list starting at location i