Lab 6
Lab 6
Lab 06
Polymorphism
Objective(s):
1. Polymorphism
1: Polymorphism
The word polymorphism means having many forms. In simple words, that allows us to perform a
single action in different way. The word “poly” means many and “morphs” means forms, So it
means many forms.
Real life example of polymorphism: A person at the same time can have different
characteristic. Like a woman at the same time is a mother, a daughter or an employee. So the
same person posses different behavior in different situations. This is called polymorphism.
In computer science, it describes the concept that objects of different types can be accessed
through the same interface.
Polymorphism in Java only occurs when there are one or more classes or objects related to each
other by inheritance (method overriding).
static or compile-time
dynamic or runtime polymorphism
Static Polymorphism:
Java, like many other object-oriented programming languages, allows you to implement multiple
methods within the same class that use the same name but a different set of parameters (method
with different signature). That is called method overloading and represents a static form of
polymorphism.
At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding.
class DemoOverload{
public int add(int x, int y){ //method 1
1
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
return x+y;
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}
In the above example, there are four versions of add methods. The first method takes two
parameters while the second one takes three. For the third and fourth methods, there is a change
of order of parameters. The compiler looks at the method signature and decides which method to
invoke for a particular method call at compile time.
Dynamic Polymorphism:
This form of polymorphism doesn’t allow the compiler to determine the executed method. The
JVM needs to do that at runtime hence also known as Runtime Polymorphism.
Within an inheritance hierarchy, a subclass can override a method of its superclass. That enables
the developer of the subclass to customize or completely replace the behavior of that method.
It also creates a form of polymorphism. Both methods, implemented by the super- and subclass,
share the same name and parameters (method with same signature) but provide different
functionality.
Method overriding is one of the ways in which Java supports Runtime Polymorphism. Dynamic
method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time.
2
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
SuperClass
extends
SubClass
Upcasting
class A{}
class B extends A{}
A a = new B();//upcasting
class Vehicle{
public void move(){
System.out.println(“Vehicles can move!!”);
}
}
class Test{
public static void main(String[] args){
3
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
vh=new Vehicle();
vh.move(); // prints Vehicles can move!!
}
}
Simply, one can say that overridden method is called through a reference of parent class, then
type of the object determines which method is to be executed .
4
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
Polymorphism at work (all known as run-time binding)
5
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
Lab Tasks:
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.
• Being the base class, Employee class contains the common behavior. Add firstName,
lastName and CNIC as attributes of type String
6
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: 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 ; }
• Define earning() method as shown below
public double earnings( ) { return 0.00; }
7
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
• 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; }
• 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(); }
Exercise 1(b)
8
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
"222-22-2222", 10000, 0.06 );
Employee thirdEmployee = new BasePlusCommissionEmployee("Fabeeha",
"Fatima", "333-33-3333", 5000 , 0.04 , 300 );
Exercise 2
Create a Parent Class name Animal with instance variable name, age and gender, also a method
name ProduceSound().
1. Create child classes of Animal Dog, Frog, Kitten and Tomcat. Dog, Frog, Cats are
animal. Kittens are female cats and Tomcats are male cats. Define useful constructors
and methods.
9
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism
2. Modify the ProduceSound() method inherited by child class by its type "e.g for Dog
ProduceSound("Bow wow")".
Hint: method OverRiding will be used( MayBe just a keyWord would be used
and everything else would be same as parent class).
3. Create an array of different kind of animals and calculate the average age of each kind of
animals. (hint: you can use instanceOf method for this task)
10
Department of Computer Science
CSC-150 – Object Oriented Programming Lab 06: Polymorphism