th edition lewis & loftus java - clark ucs120/lectures/jsl_chap09.pdfpolymorphism via...

23
1 Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved © 2007 Pearson Addison-Wesley. All rights reserved 9-2 Polymorphism Polymorphism is an object-oriented concept that allows us to create versatile software designs Chapter 9 focuses on: defining polymorphism and its benefits using inheritance to create polymorphic references using interfaces to create polymorphic references using polymorphism to implement sorting and searching algorithms additional GUI components

Upload: others

Post on 10-Mar-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

1

Chapter 9Polymorphism

5TH EDITION

Lewis & LoftusjavaSoftware Solutions

Foundations of Program Design

© 2007 Pearson Addison-Wesley. All rights reserved

© 2007 Pearson Addison-Wesley. All rights reserved 9-2

Polymorphism

• Polymorphism is an object-oriented concept that allows us to create versatile software designs

• Chapter 9 focuses on:

defining polymorphism and its benefitsusing inheritance to create polymorphic referencesusing interfaces to create polymorphic referencesusing polymorphism to implement sorting and searching algorithmsadditional GUI components

Page 2: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

2

© 2007 Pearson Addison-Wesley. All rights reserved 9-3

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching (skipped)

Event Processing Revisited (skipped)

File Choosers and Color Choosers (skipped)

Sliders (skipped)

© 2007 Pearson Addison-Wesley. All rights reserved 9-4

Binding• Consider the following method invocation:

obj.doIt();

• At some point, this invocation is bound to the definition of the method that it invokes

• If this binding occurred at compile time, then that line of code would call the same method every time

• However, Java defers method binding until run time -- this is called dynamic binding or run time binding

• Dynamic binding provides flexibility in program design

Page 3: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

3

© 2007 Pearson Addison-Wesley. All rights reserved 9-5

Polymorphism

• The term polymorphism literally means "having many forms"

• A polymorphic reference is a variable that can refer to different types of objects at different points in time

• The method invoked through a polymorphic reference can change from one invocation to the next

• All object references in Java are potentially polymorphic

© 2007 Pearson Addison-Wesley. All rights reserved 9-6

Polymorphism

• Suppose we create the following reference variable:

Occupation job;

• Java allows this reference to point to an Occupation object, or to any object of any compatible type

• This compatibility can be established using inheritance or using interfaces

• Careful use of polymorphic references can lead to elegant, robust software designs

Page 4: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

4

© 2007 Pearson Addison-Wesley. All rights reserved 9-7

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching

Event Processing Revisited

File Choosers and Color Choosers

Sliders

© 2007 Pearson Addison-Wesley. All rights reserved 9-8

References and Inheritance

• An object reference can refer to an object of its class, or to an object of its child class

• For example, if the Holiday class is used to derive a class called Christmas, then a Holiday reference could be used to point to a Christmas object

Holiday day;day = new Christmas();

Holiday

Christmas

Page 5: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

5

© 2007 Pearson Addison-Wesley. All rights reserved 9-9

References and Inheritance

• Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment

• Assigning an parent object to a child reference can be done also, but it is considered a narrowing conversion and must be done with a cast

• The widening conversion is the most useful

© 2007 Pearson Addison-Wesley. All rights reserved 9-10

Polymorphism via Inheritance

• It is the type of the object being referenced, not the reference type, that determines which method is invoked

• Suppose the Holiday class has a method called celebrate, and the Christmas class overrides it

• Now consider the following invocation:day.celebrate();

• If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmasversion

Page 6: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

6

© 2007 Pearson Addison-Wesley. All rights reserved 9-11

Polymorphism via Inheritance

• Consider the following class hierarchy:StaffMember

Executive Hourly

Volunteer Employee

© 2007 Pearson Addison-Wesley. All rights reserved 9-12

Polymorphism via Inheritance

• Now let's look at an example that pays a set of diverse employees using a polymorphic method

• See Firm.java (page 488)• See Staff.java (page 489)• See StaffMember.java (page 491)• See Volunteer.java (page 493)• See Employee.java (page 494)• See Executive.java (page 495)• See Hourly.java (page 496)

Page 7: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

7

© 2007 Pearson Addison-Wesley. All rights reserved 9-13

Firm.java

//********************************************************************// Firm.java Author: Lewis/Loftus//// Demonstrates polymorphism via inheritance.//********************************************************************

public class Firm{

//-----------------------------------------------------------------// Creates a staff of employees for a firm and pays them.//-----------------------------------------------------------------public static void main (String[] args){

Staff personnel = new Staff();

personnel.payday();}

}

© 2007 Pearson Addison-Wesley. All rights reserved 9-14

Staff.javapublic class Staff{

private StaffMember[] staffList;//-----------------------------------------------------------------// Constructor: Sets up the list of staff members.//-----------------------------------------------------------------public Staff (){

staffList = new StaffMember[6];

staffList[0] = new Executive ("Sam", "123 Main Line","555-0469", "123-45-6789", 2423.07);

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);

staffList[3] = new Hourly ("Diane", "678 Fifth Ave.","555-0690", "958-47-3625", 10.55);

staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.","555-8374");

staffList[5] = new Volunteer ("Cliff", "321 Duds Lane","555-7282");

((Executive)staffList[0]).awardBonus (500.00);((Hourly)staffList[3]).addHours (40);

}

Page 8: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

8

© 2007 Pearson Addison-Wesley. All rights reserved 9-15

Staff.java (cont.)

//-----------------------------------------------------------------// Pays all staff members.//-----------------------------------------------------------------public void payday (){

double amount;

for (int count=0; count < staffList.length; count++){

System.out.println (staffList[count]);

amount = staffList[count].pay(); // polymorphic

if (amount == 0.0)System.out.println ("Thanks!");

elseSystem.out.println ("Paid: " + amount);

System.out.println ("-----------------------------------");}

}}

© 2007 Pearson Addison-Wesley. All rights reserved 9-16

StaffMember.java//********************************************************************// StaffMember.java Author: Lewis/Loftus//// Represents a generic staff member.//********************************************************************abstract public class StaffMember{

protected String name;protected String address;protected String phone;//-----------------------------------------------------------------// Constructor: Sets up this staff member using the specified// information.//-----------------------------------------------------------------public StaffMember (String eName, String eAddress, String ePhone){

name = eName;address = eAddress;phone = ePhone;

}public String toString() { …. }

//-----------------------------------------------------------------// Derived classes must define the pay method for each type of// employee.//-----------------------------------------------------------------public abstract double pay();

}

Page 9: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

9

© 2007 Pearson Addison-Wesley. All rights reserved 9-17

Volunteer.java//********************************************************************// Volunteer.java Author: Lewis/Loftus//// Represents a staff member that works as a volunteer.//********************************************************************

public class Volunteer extends StaffMember{

//-----------------------------------------------------------------// Constructor: Sets up this volunteer using the specified// information.//-----------------------------------------------------------------public Volunteer (String eName, String eAddress, String ePhone){

super (eName, eAddress, ePhone);}

//-----------------------------------------------------------------// Returns a zero pay value for this volunteer.//-----------------------------------------------------------------public double pay(){

return 0.0;}

}

© 2007 Pearson Addison-Wesley. All rights reserved 9-18

Employee.java//********************************************************************// Employee.java Author: Lewis/Loftus// Represents a general paid employee.//********************************************************************

public class Employee extends StaffMember{

protected String socialSecurityNumber;protected double payRate;

//-----------------------------------------------------------------// Constructor: Sets up this employee with the specified// information.//-----------------------------------------------------------------public Employee (String eName, String eAddress, String ePhone, String socSecNumber, double rate){

super (eName, eAddress, ePhone);socialSecurityNumber = socSecNumber;payRate = rate;

}//-----------------------------------------------------------------

// Returns the pay rate for this employee.//-----------------------------------------------------------------public double pay(){

return payRate;}

…}

Page 10: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

10

© 2007 Pearson Addison-Wesley. All rights reserved 9-19

Executive.java

//********************************************************************// Executive.java Author: Lewis/Loftus//// Represents an executive staff member, who can earn a bonus.//********************************************************************

public class Executive extends Employee{

private double bonus;

//-----------------------------------------------------------------// Constructor: Sets up this executive with the specified// information.//-----------------------------------------------------------------public Executive (String eName, String eAddress, String ePhone,

String socSecNumber, double rate){

super (eName, eAddress, ePhone, socSecNumber, rate);

bonus = 0; // bonus has yet to be awarded}

© 2007 Pearson Addison-Wesley. All rights reserved 9-20

Executive.java (cont.)

//-----------------------------------------------------------------// Awards the specified bonus to this executive.//-----------------------------------------------------------------public void awardBonus (double execBonus){

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;

return payment;}

}

Page 11: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

11

© 2007 Pearson Addison-Wesley. All rights reserved 9-21

Hourly.java//********************************************************************// Hourly.java Author: Lewis/Loftus//// Represents an employee that gets paid by the hour.//********************************************************************

public class Hourly extends Employee{

private int hoursWorked;//-----------------------------------------------------------------// Constructor: 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;

}…

© 2007 Pearson Addison-Wesley. All rights reserved 9-22

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching

Event Processing Revisited

File Choosers and Color Choosers

Sliders

Page 12: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

12

© 2007 Pearson Addison-Wesley. All rights reserved 9-24

Interfaces – from Chap. 6

• A Java interface is a collection of abstract methods and constants

• An abstract method is a method header without a method body

• An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, usually it is left off

• An interface is used to establish a set of methods that a class will implement

© 2007 Pearson Addison-Wesley. All rights reserved 9-25

Interfaces

public interface Doable{

public void doThis();public int doThat();public void doThis2 (float value, char ch);public boolean doTheOther (int num);

}

interface is a reserved wordNone of the methods inan interface are given

a definition (body)

A semicolon immediatelyfollows each method header

Page 13: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

13

© 2007 Pearson Addison-Wesley. All rights reserved 9-26

Interfaces

• An interface cannot be instantiated

• Methods in an interface have public visibility by default

• A class formally implements an interface by:

stating so in the class header

providing implementations for each abstract method in the interface

• If a class asserts that it implements an interface, it must define all methods in the interface

© 2007 Pearson Addison-Wesley. All rights reserved 9-27

Interfaces

public class CanDo implements Doable{

public void doThis (){

// whatever}

public void doThat (){

// whatever}

// etc.}

implements is areserved word

Each method listedin Doable is

given a definition

Page 14: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

14

© 2007 Pearson Addison-Wesley. All rights reserved 9-28

Interfaces

• A class that implements an interface can implement other methods as well

• See Complexity.java (page 315)• See Question.java (page 316)• See MiniQuiz.java (page 318)

• In addition to (or instead of) abstract methods, an interface can contain constants

• When a class implements an interface, it gains access to all its constants

© 2007 Pearson Addison-Wesley. All rights reserved 9-29

Interfaces

• A class can implement multiple interfaces

• The interfaces are listed in the implements clause

• The class must implement all methods in all interfaces listed in the header

class ManyThings implements interface1, interface2{

// all methods of both interfaces}

Page 15: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

15

© 2007 Pearson Addison-Wesley. All rights reserved 9-30

Interfaces

• The Java standard class library contains many helpful interfaces

• The Comparable interface contains one abstract method called compareTo, which is used to compare two objects

• We discussed the compareTo method of the String class in Chapter 5

• The String class implements Comparable, giving us the ability to put strings in lexicographic order

© 2007 Pearson Addison-Wesley. All rights reserved 9-31

The Comparable Interface

• Any class can implement Comparable to provide a mechanism for comparing objects of that typeif (obj1.compareTo(obj2) < 0)

System.out.println ("obj1 is less than obj2");

• The value returned from compareTo should be negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2

• When a programmer designs a class that implements the Comparable interface, it should follow this intent

Page 16: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

16

© 2007 Pearson Addison-Wesley. All rights reserved 9-32

The Comparable Interface

• It's up to the programmer to determine what makes one object less than another

• For example, you may define the compareTomethod of an Employee class to order employees by name (alphabetically) or by employee number

• The implementation of the method can be as straightforward or as complex as needed for the situation

© 2007 Pearson Addison-Wesley. All rights reserved 9-35

Interfaces

• You could write a class that implements certain methods (such as compareTo) without formally implementing the interface (Comparable)

• However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways

• Interfaces are a key aspect of object-oriented design in Java

Page 17: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

17

© 2007 Pearson Addison-Wesley. All rights reserved 9-36

Polymorphism via Interfaces –Chap. 9 again• An interface name (such as Speaker) can be used

as the type of an object reference variable

Speaker current;

• The current reference can be used to point to any object of any class that implements the Speakerinterface

• The version of speak that the following line invokes depends on the type of object that current is referencing

current.speak();

© 2007 Pearson Addison-Wesley. All rights reserved 9-37

Polymorphism via Interfaces

• Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method

• In the following code, the first call to speakinvokes one version and the second invokes another:

Speaker guest = new Philospher();guest.speak();guest = new Dog();guest.speak();

Page 18: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

18

© 2007 Pearson Addison-Wesley. All rights reserved 9-38

Outline

Polymorphic References

Polymorphism via Inheritance

Polymorphism via Interfaces

Sorting

Searching

Event Processing Revisited

File Choosers and Color Choosers

Sliders

© 2007 Pearson Addison-Wesley. All rights reserved 9-39

Sorting

• Sorting is the process of arranging a list of items in a particular order

• The sorting process is based on specific value(s)

sorting a list of test scores in ascending numeric ordersorting a list of people alphabetically by last name

• There are many algorithms, which vary in efficiency, for sorting a list of items

• We will examine two specific algorithms:

Selection SortInsertion Sort (skipped)

Page 19: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

19

© 2007 Pearson Addison-Wesley. All rights reserved 9-40

Selection Sort

• The approach of Selection Sort:

select a value and put it in its final place into the listrepeat for all other values

• In more detail:

find the smallest value in the listswitch it with the value in the first positionfind the next smallest value in the listswitch it with the value in the second positionrepeat until all values are in their proper places

(note in the InvToCS book, the algorithm is described as putting the largest number in place first)

© 2007 Pearson Addison-Wesley. All rights reserved 9-41

Selection Sort

• An example:original: 3 9 6 1 2smallest is 1: 1 9 6 3 2smallest is 2: 1 2 6 3 9smallest is 3: 1 2 3 6 9smallest is 6: 1 2 3 6 9

• Each time, the smallest remaining value is found and exchanged with the element in the "next" position to be filled

Page 20: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

20

© 2007 Pearson Addison-Wesley. All rights reserved 9-42

Swapping

• The processing of the selection sort algorithm includes the swapping of two values

• Swapping requires three assignment statements and a temporary storage location:

temp = first;first = second;second = temp;

© 2007 Pearson Addison-Wesley. All rights reserved 9-43

Polymorphism in Sorting

• Recall that an class that implements the Comparable interface defines a compareTomethod to determine the relative order of its objects

• We can use polymorphism to develop a generic sort for any set of Comparable objects

• The sorting method accepts as a parameter an array of Comparable objects

• That way, one method can be used to sort a group of People, or Books, or whatever

Page 21: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

21

© 2007 Pearson Addison-Wesley. All rights reserved 9-44

Selection Sort

• The sorting method doesn't "care" what it is sorting, it just needs to be able to call the compareTo method

• That is guaranteed by using Comparable as the parameter type

• Also, this way each class decides for itself what it means for one object to be less than another

• See PhoneList.java (page 502)• See Sorting.java (page 503), specifically the selectionSort method

• See Contact.java (page 505)

© 2007 Pearson Addison-Wesley. All rights reserved 9-45

PhoneList.java//********************************************************************// PhoneList.java Author: Lewis/Loftus//// Driver for testing a sorting algorithm.//********************************************************************public class PhoneList{

//-----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints// them.//-----------------------------------------------------------------public static void main (String[] args){

Contact[] friends = new Contact[8];

friends[0] = new Contact ("John", "Smith", "610-555-7384");friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");friends[2] = new Contact ("Mark", "Riley", "733-555-2969");friends[3] = new Contact ("Laura", "Getz", "663-555-3984");friends[4] = new Contact ("Larry", "Smith", "464-555-3489");friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");friends[6] = new Contact ("Mario", "Guzman", "804-555-9066");friends[7] = new Contact ("Marsha", "Grant", "243-555-2837");

Sorting.selectionSort(friends);for (Contact friend : friends)

System.out.println (friend);}

}

Page 22: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

22

© 2007 Pearson Addison-Wesley. All rights reserved 9-46

Sorting.java//********************************************************************// Sorting.java Author: Lewis/Loftus//// Demonstrates the selection sort and insertion sort algorithms.//********************************************************************public class Sorting{

//-----------------------------------------------------------------// Sorts the specified array of objects using the selection// sort algorithm.//-----------------------------------------------------------------public static void selectionSort (Comparable[] list){

int min;Comparable temp;

for (int index = 0; index < list.length-1; index++){

min = index;for (int scan = index+1; scan < list.length; scan++)

if (list[scan].compareTo(list[min]) < 0)min = scan;

// Swap the valuestemp = list[min];list[min] = list[index];list[index] = temp;

}}

© 2007 Pearson Addison-Wesley. All rights reserved 9-47

Contact.java

//********************************************************************// Contact.java Author: Lewis/Loftus//// Represents a phone contact.//********************************************************************

public class Contact implements Comparable{

private String firstName, lastName, phone;

//-----------------------------------------------------------------// Constructor: Sets up this contact with the specified data.//-----------------------------------------------------------------public Contact (String first, String last, String telephone){

firstName = first;lastName = last;phone = telephone;

}

Page 23: TH EDITION Lewis & Loftus java - Clark Ucs120/lectures/jsl_chap09.pdfPolymorphism via Inheritance • Now let's look at an example that pays a set of diverse employees using a polymorphic

23

© 2007 Pearson Addison-Wesley. All rights reserved 9-48

Contact.java

//-----------------------------------------------------------------// Uses both last and first names to determine ordering.//-----------------------------------------------------------------public int compareTo (Object other){

int result;

String otherFirst = ((Contact)other).getFirstName();String otherLast = ((Contact)other).getLastName();

if (lastName.equals(otherLast))result = firstName.compareTo(otherFirst);

elseresult = lastName.compareTo(otherLast);

return result;}

© 2007 Pearson Addison-Wesley. All rights reserved 9-67

Summary

• Chapter 9 has focused on:

defining polymorphism and its benefitsusing inheritance to create polymorphic referencesusing interfaces to create polymorphic referencesusing polymorphism to implement selection sort