CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Lab08: Polymorphism
In this lab, the following topics will be covered:
1. Polymorphism
2. upcasting and downcasting
3. instanceof operator
4. Exercise for practice
Exercises
Example
Create a payroll system using classes, inheritance and polymorphism
Four types of employees paid weekly
1. Salaried employees: fixed salary irrespective of hours
2. Hourly employees: 40 hours salary and overtime (> 40 hours)
3. Commission employees: paid by a percentage of sales
4. Base-plus-commission employees: base salary and a percentage of sales
The information know about each employee is his/her first name, last name and national identity card
number. The reset depends on the type of employee.
Step
by Step Guidelines
Step 1: Define Employee Class
Being the base class, Employee class contains the common behavior. Add firstName, lastName and
CNIC as attributes of type String
Provide getter & setters for each attribute
Write default & parameterized constructors
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Override toString() method as shown below
public String toString( ) {
return firstName + “ ” + lastName + “ CNIC# ” + CNIC ;
}
Define earning() method as shown below
public double earnings( )
{ return 0.00;
}
Step 2: Define SalariedEmployee Class
Extend this class from Employee class.
Add weeklySalary as an attribute of type double
Provide getter & setters for this attribute. Make sure that weeklySalary never sets to negative value. (use if )
Write default & parameterize constructor. Don’t forget to call default & parameterize constructors of
Employee class.
Override toString() method as shown below
public String toString( ) {
return “\nSalaried employee: ” + super.toString();
}
Override earning() method to implement class specific behavior as shown below
public double earnings( ) {
return weeklySalary;
}
Step 3: Define HourlyEmployee Class
Extend this class from Employee class.
Add wage and hours as attributes of type double
Provide getter & setters for these attributes. Make sure that wage and hours never set to a negative value.
Write default & parameterize constructor. Don’t forget to call default & parameterize constructors of
Employee class.
Override toString() method as shown below
public String toString( ) {
return “\nHourly employee: ” + super.toString();
}
Override earning() method to implement class specific behaviour as shown below
public double earnings( )
{ if (hours <= 40){
return wage * hours;
} }
else{ }
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
return
40*wage +
(hours-
40)*wage*1.5
;
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Step 4: Define CommissionEmployee Class
Extend this class form Employee class.
Add grossSales and commissionRate as attributes of type double
Provide getter & setters for these attributes. Make sure that grossSales and commissionRate never set to
a negative value.
Write default & parameterize constructor. Don’t forget to call default & parameterize
constructors of Employee class.
Override toString() method as shown below
public String toString( ) {
return “\nCommission employee: ” + super.toString();
}
Override earning() method to implement class specific behaviour as shown below
public double earnings( ) {
return grossSales * commisionRate;
}
Step 5: Define BasePlusCommissionEmployee Class
Extend this class form CommissionEmployee class not from Employee class. Why? Think on it by
yourself
Add baseSalary as an attribute of type double
Provide getter & setters for these attributes. Make sure that baseSalary never sets to negative value.
Write default & parameterize constructor. Don’t forget to call default & parameterize
constructors of Employee class.
Override toString() method as shown below
public String toString( ) {
return “\nBase plus Commission employee: ” + super.toString();
}
Override earning() method to implement class specific behaviour as shown below
public double earnings( ) {
return baseSalary + super.earning();
}
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Step 6: Putting it all Together
public class PayRollSystemTest {
public static void main (String [] args) {
Employee firstEmployee = new SalariedEmployee("Usman"
,"Ali","111- 11-1111", 800.00 );
Employee secondEmployee = new CommissionEmployee("Atif" ,"Aslam",
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
"222-22-2222", 10000, 0.06 );
Employee thirdEmployee = new
BasePlusCommissionEmployee("Rana", "Naseeb", "333-33-3333", 5000
, 0.04 , 300 );
Employee fourthEmployee = new HourlyEmployee( "Renson" ,
"Isaac", "444-44-4444" , 16.75 , 40 );
// polymorphism: calling toString() and earning() on Employee’s
reference
System.out.println(firstEmployee);
System.out.println(firstEmployee.earnings());
System.out.println(secondEmployee);
System.out.println(secondEmployee.earnings());
System.out.println(thirdEmployee);
// performing downcasting to access & raise base
salary BasePlusCommissionEmployee currentEmployee =
(BasePlusCommissionEmployee) thirdEmployee;
double oldBaseSalary = currentEmployee.getBaseSalary();
System.out.println( "old base salary: " + oldBaseSalary)
;
currentEmployee.setBaseSalary(1.10 * oldBaseSalary);
System.out.println("new base salary with 10% increase
is:"+
currentEmployee.getBaseSalary());
System.out.println(thirdEmployee.earnings() );
System.out.println(fourthEmployee);
System.out.println(fourthEmployee.earnings() );
} // end main
} // end class
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Example
Implement classes: Shape, Circle and Rectangle based on the class diagram and description below:
Class Point implementation is given as follow:
class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x;}
public int getY() { return y;}
public double distanceTo(Point p) {
return Math.sqrt((x-p.getX())*(x-p.getX())+
(y-p.getY())*(y-p.getY()));
}
public String toString() {
return "("+x+", "+y+")";
}
}
Class Shape has:
An attributes of type Point, specifies the center of the shape object.
A constructor that allows to initialize the center attribute with the value of the passed parameter
A method that takes an object of type Point as a parameter and returns true if the point resides within
the shape’s area, and false otherwise.
Class Circle has:
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
An attribute of type integer specifies the radius measure of the circle
A constructor that takes a Point parameter to initialize the center and an integer parameter to initialize
the radius
A getRadius method to return the value of the attribute radius
An overriding version of toString method to return the attribute values of a Circle object as
String Class Rectangle has:
Two integer attributes represents the length and width of the Rectangle object
A constructor to initialize the center, length and width attribute for a new Rectangle object
Methods getLength and getWidth returns the values of attributes length and width respectively
An overriding version of toString method to return the attribute values of a Rectangle object as a String
Class ShapesArray
displayrectsinfo() display all rectangles information
getCirclecounter():int return the number of circles
getAvgAreas():double return the average area of all shapes
removeallrect() delete all rectangles
Step 6: Putting it all Together
Implementation TestShape as given.
create ShapesArray object with size=20
display these options
1. add new shape
a. for rectangle (ask for details)
b. for circle (ask for details)
2. display all rectangles
3. display the average shapes area
4. display the number of circles
5. remove all rectangles
6. exit
CSL-210: Object-Oriented
Programming Lab
BS(IT)- Semester 02
Engr. Saba
Exercise 1
You are developing a vehicle rental system for a company that rents cars, bikes, and trucks. Each vehicle has
different rental rates and features.
Create a base Vehicle class with common properties like rentalPrice and licensePlate.
Use polymorphism to create subclasses (Car, Bike, and Truck) that override a method
calculateRentalCost(int days) to provide different pricing for each vehicle type.
Demonstrate polymorphism by creating an array of Vehicle objects and calculating rental costs for different
vehicle types using a loop.
Exercise 2
You are creating a simulation for a zoo where different animals have unique sounds. The system should be able to
call the correct sound for each animal without checking its type explicitly.
Create an abstract class Animal with a method makeSound().
Create subclasses such as Lion, Elephant, and Monkey, each with its unique implementation of makeSound().
Write a method that accepts a list of Animal objects and loops through them to call makeSound() on each one,
demonstrating polymorphism.
Exercise 3
You are tasked with creating a grading system for a university. The system needs to handle different grading
schemes based on course type: TheoreticalCourse, LabCourse, and ProjectCourse. Each type of course calculates
the final grade differently.
Create an abstract Course class with a calculateFinalGrade() method.
Implement subclasses TheoreticalCourse, LabCourse, and ProjectCourse where each subclass overrides
calculateFinalGrade() according to the specific grading requirements for that course type.
Write a main method to create different types of Course objects and calculate grades, demonstrating
polymorphism by calling calculateFinalGrade() on each object.