Lab Polymorphism
Lab Polymorphism
Objective:
What is Polymorphism?
Polymorphism enables us to "program in the general" rather than "program in the specific." In
particular, polymorphism enables us to write programs that process objects that share the same
superclass in a class hierarchy as if they are all objects of the superclass; this can simplify
programming.
Consider the following example of polymorphism. Suppose we create a program that simulates
the movement of several types of animals for a biological study. Classes Fish, Frog and Bird
represent the three types of animals under investigation. Imagine that each of these classes
extends superclass Animal, which contains a method move and maintains an animal's current
location as x-y coordinates. Each subclass implements method move. Our program maintains an
array of references to objects of the various Animal subclasses. To simulate the animals'
movements, the program sends each object the same message once per secondnamely, move.
However, each specific type of Animal responds to a move message in a unique waya Fish
might swim three feet, a Frog might jump five feet and a Bird might fly ten feet. The program
issues the same message (i.e., move) to each animal object generically, but each object knows
how to modify its x-y coordinates appropriately for its specific type of movement. Relying on
each object to know how to "do the right thing" (i.e., do what is appropriate for that type of
object) in response to the same method call is the key concept of polymorphism. The same
message (in this case, move) sent to a variety of objects has "many forms" of resultshence the
term polymorphism
A company pays its employees on a weekly basis. The employees are of four types: Salaried
employees are paid a fixed weekly salary regardless of the number of hours worked, hourly
employees are paid by the hour and receive overtime pay for all hours worked in excess of 40
hours, commission employees are paid a percentage of their sales and salaried-commission
employees receive a base salary plus a percentage of their sales. For the current pay period,
the company has decided to reward salaried-commission employees by adding 10% to their
base salaries. The company wants to implement a Java application that performs its payroll
calculations polymorphically.
Employee Abstract Class:
// set salary
public void setWeeklySalary( double salary )
{
weeklySalary = salary < 0.0 ? 0.0 : salary;
} // end method setWeeklySalary
// return salary
public double getWeeklySalary()
{
return weeklySalary;
} // end method getWeeklySalary
// set wage
public void setWage( double hourlyWage )
{
wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage;
} // end method setWage
// return wage
public double getWage()
{
return wage;
} // end method getWage
}
Main Class
}
}}