Lab 08 - Polymorphism
Lab 08 - Polymorphism
Programming
Semester BS CS – 02
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
Exercise 1 (a)
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
Being the base class, Employee class contains the common behavior. Add firstName, lastName
and CNIC as attributes of type String
Department of Computer Sciences Semester BSCS 2
CSL-210 Object Oriented Programming Lab 08: Polymorphism
Provide getter & setters for each attribute
Write default & parameterized constructors
Override toString() method as shown below
public String toString( ) {
return firstName + “ ” + lastName + “ CNIC# ” + CNIC ;
}
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();
}
Exercise 1 (b)
System.out.println(thirdEmployee);
// performing downcasting to access & raise base salary
BasePlusCommissionEmployee currentEmployee =
(BasePlusCommissionEmployee) thirdEmployee;
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
Implement classes: Shape, Circle and Rectangle based on the class diagram and description below:
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+")";
}
}
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
Exercise 2 (b)
Project
From last week you have found the Inheritance between the classes and now find the
Polymorphism in your classes.