0% found this document useful (0 votes)
56 views30 pages

7 Polymorphism

The document discusses the concept of polymorphism in object-oriented programming. It defines polymorphism as allowing objects to take on multiple forms, and explains that polymorphism is achieved through polymorphic references which can refer to objects of different types over time. The document outlines that polymorphism is implemented through inheritance, where child classes can override methods from parent classes, and interfaces, allowing for common method definitions across unrelated classes. It provides code examples of a class hierarchy implementing polymorphism through inheritance, with a base StaffMember class and derived Employee, Volunteer, Executive and Hourly classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views30 pages

7 Polymorphism

The document discusses the concept of polymorphism in object-oriented programming. It defines polymorphism as allowing objects to take on multiple forms, and explains that polymorphism is achieved through polymorphic references which can refer to objects of different types over time. The document outlines that polymorphism is implemented through inheritance, where child classes can override methods from parent classes, and interfaces, allowing for common method definitions across unrelated classes. It provides code examples of a class hierarchy implementing polymorphism through inheritance, with a base StaffMember class and derived Employee, Volunteer, Executive and Hourly classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 30

Polymorphism

© 2004 Pearson Addison-Wesley. All rights reserved 9-1


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

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


Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces

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


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 late
binding
• Late binding provides flexibility in program design
© 2004 Pearson Addison-Wesley. All rights reserved 9-4
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

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


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

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


Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces

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


References and Inheritance
• An object reference can refer to an object of its
class, or to an object of any class related to it by
inheritance

• For example, if the Holiday class is derived from a


class called day, then a day reference could be
used to point to a Holiday object

Day
Day day;
day = new Holiday();
Holiday

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


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

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


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

• Suppose the Day class has a method called


celebrate, and the Holiday class overrides it

• Now consider the following invocation:

day.celebrate();

• If day refers to a Day object, it invokes the Day


version of celebrate; if it refers to a Holiday
object, it invokes the Holiday version

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


Polymorphism via Inheritance
• Consider the following class hierarchy:

StaffMember

Volunteer Employee

Executive Hourly

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


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


• See Staff.java (page 487)
• See StaffMember.java (page 489)
• See Volunteer.java (page 491)
• See Employee.java (page 492)
• See Executive.java (page 493)
• See Hourly.java (page 494)

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


StaffMember.java
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;
}

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


StaffMember.java
//----------------------------------------------------------
// Returns a string including the basic employee
// information.
//----------------------------------------------------------
public String toString()
{
String result = "Name: " + name + "\n";

result += "Address: " + address + "\n";


result += "Phone: " + phone;

return result;
}

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

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


Volunteer.java
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;
}
}

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


Employee.java
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;
}

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


Employee.java
//----------------------------------------------------------
// Returns information about an employee as a string.
//----------------------------------------------------------
public String toString()
{
String result = super.toString();

result += "\nSocial Security Number: " +


socialSecurityNumber;

return result;
}

//----------------------------------------------------------
// Returns the pay rate for this employee.
//----------------------------------------------------------
public double pay()
{
return payRate;
}
}

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


Executive.java
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


}

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


Executive.java
//----------------------------------------------------------
// 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;
}
}

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


Hourly.java
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;
}

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


Hourly.java
//----------------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours.
//----------------------------------------------------------
public void addHours (int moreHours)
{
hoursWorked += moreHours;
}

//----------------------------------------------------------
// Computes and returns the pay for this hourly employee.
//----------------------------------------------------------
public double pay()
{
double payment = payRate * hoursWorked;

hoursWorked = 0;

return payment;
}

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


Hourly.java
//----------------------------------------------------------
// Returns information about this hourly employee as a
// string.
//----------------------------------------------------------
public String toString()
{
String result = super.toString();

result += "\nCurrent hours: " + hoursWorked;

return result;
}
}

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


Staff.java
public 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);

© 2004 Pearson Addison-Wesley. All rights reserved 9-23


Staff.java
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);
}

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


Staff.java
//----------------------------------------------------------
// Pays all staff members.
//----------------------------------------------------------
public void payday ()
{
double amount;

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


{
System.out.println (staffList[count]); // polymorphic

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

if (amount == 0.0)
System.out.println ("Thanks!");
else
System.out.println ("Paid: " + amount);

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

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


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

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


Output
Name: Sam Name: Diane
Address: 123 Main Line Address: 678 Fifth Ave.
Phone: 555-0469 Phone: 555-0690
Social Security Number: 123-45-6789 Social Security Number: 958-47-3625
Paid: 2923.07 Current hours: 40
----------------------------------- Paid: 422.0
Name: Carla -----------------------------------
Address: 456 Off Line Name: Norm
Phone: 555-0101 Address: 987 Suds Blvd.
Social Security Number: 987-65-4321 Phone: 555-8374
Paid: 1246.15 Thanks!
----------------------------------- -----------------------------------
Name: Woody Name: Cliff
Address: 789 Off Rocker Address: 321 Duds Lane
Phone: 555-0000 Phone: 555-7282
Social Security Number: 010-20-3040 Thanks!
Paid: 1169.23 -----------------------------------
-----------------------------------

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


Outline
Polymorphic References
Polymorphism via Inheritance
Polymorphism via Interfaces

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


Polymorphism via Interfaces
• An interface name 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 Speaker
interface

• The version of speak that the following line


invokes depends on the type of object that
current is referencing

current.speak();

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


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 speak


invokes one version and the second invokes
another:
Speaker guest = new Philospher();
guest.speak();
guest = new Dog();
guest.speak();

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

You might also like