You are on page 1of 14

PAF- KARACHI INSTITUTE OF ECONOMICS & TECHNOLOGY

College of Engineering

(Software Engineering)

CS1305 – Object Oriented Programming

Semester: ______________________ Date of Experiment: _____________________


Student name: __________________ Faculty Signature: ______________________

Lab07 Polymorphism

PLO1 – Engineering Knowledge C1 – Recall


PLOs PLO4 - Investigate Bloom’s Taxonomy C4 - Analyze
PLO8 – Ethics P2 – Set
LAB TASK PERFORMANCE
Excellent Average Poor
CLO’s Aspects of Assessments Marks
(75-100%) (50-75%) (<50%)
Recall Recall the associated Student lacks clear
CLO1
Complete understanding of Complete understanding of the
concepts form theory understanding of concepts of
10% the concepts of OOP / actively concepts of OOP / less actively
regarding basic concepts of OOP/ Unable to read and
participate during lecture. participate during lecture.
OOP. interpret it.
Experimental Validation
Correctly select the technique Correctly select the technique
Select an appropriate and
and core concept of OOP to and core concept of OOP to
suitable OOP core concept to Don’t able to write a logic and
CLO6 perform particular task (real perform particular task (real
80%
solve and implement real code for the required output and
world modelling) and validate world modelling) but code
world examples to validate the as per given in a task.
the working of code have some minor errors.
working of different
conceptions of OOP
Lab Safety Properly handle
CLO7 Properly handle lab equipment Moderate level lab handling Minor or no safety measurements
10%
lab infrastructure/safety
& obey safety measures. and safety measurements has been considered.
precautions
Total Marks: 10
Student ID: ____________________ Remarks/Comments: ____________________
Objective:
1) Make attendee grasp the concept of Polymorphism in OOP.
2) Make attendee familiar with compile time and run time polymorphism.
3) Make attendee differentiate between method overloading and method over-riding.

Polymorphism:
Polymorphism is a Greek word, meaning "one name many forms". In other words, one object has many
forms or has one name with multiple functionalities. "Poly" means many and "morph" means forms.
Polymorphism provides the ability to a class to have multiple implementations with the same name. It is
one of the core principles of Object Oriented Programming after encapsulation and inheritance.

Polymorphism provides following features:


 It has the ability for classes to provide different implementations of methods that are called through
the same name.
 It allows you to invoke methods of derived class through base class reference during runtime.

There are two types of polymorphism in C#:


 Static / Compile Time Polymorphism.
 Dynamic / Runtime Polymorphism.

Static Polymorphism:
It is also known as Early Binding. It is called Compile Time Polymorphism because the decision of which
method is to be called is made at compile time.
Method overloading is an example of Static Polymorphism. In overloading, the method/function has a
same name but different signatures. The parameter sets have to differ in at least one of the following three
criteria:
 They need to have a different number of parameters, e.g. one method accepts 2 and another one 3
parameters.
 The types of the parameters need to be different, e.g. one method accepts a String and another one a
Long. Due to the different sets of parameters, each method has a different signature. That allows the
compiler to identify which method has to be called and to bind it to the method call.

There is no limit to how many overload of a method you can have. You simply declare them in a class,
just as if they were different methods that happened to have the same name. In most cases, each of these
overloaded methods provides a different but very similar functionality.
To understand it more clearly, let modify our employee example from previous labs.

5 different
implementations
for MonthlySalary
Function

Code Explanation:
From above code snippet it can be see that there are five implementations for GetMonthlySalary methods
but with different function signatures. First occurrence will calculate monthly salary only from object’s
AnnualSalay property. On the other hand second definition return monthly salary with house rent
included. Third implementation includes house rent plus conveyance allowance, forth includes additional
overtime parameter and last has an extra bonus parameter.
To use these overloaded implementation see the code below.
Calling
Overloaded
MonthlySalary
Functions

Output:

As you can see above, monthly salary has been calculated and returned by different overloaded
MonthlySalary functions, i.e. functions with same name but different signature.

When and why to use method overloading?


 Use method overloading in situation where you want a class to be able to do something, but there is
more than one possibility for what information is supplied to the method that carries out the task.
 You should consider overloading a method when you for some reason need a couple of methods that
take different parameters, but conceptually do the same thing.

Dynamic Polymorphism:

It is also known as Late Binding. In dynamic polymorphism compiler would not be aware of the method
available for overriding the functionality, so the compiler does not throw an error at compile time. Which
method to call will be decided at run-time, hence it is called Run-Time polymorphism.
Method overriding is an example of dynamic polymorphism. Here, the method name and the method
signature (number of parameters and parameter type) must be the same and but may have a different
implementation. Method overriding can be done using inheritance. With method overriding it is possible
for the base class and derived class to have the same method name and signature.
Father Person behaving Student
as

Customer
Employee

Manager Salesman

As you can see from above picture, a person can behave as many possible role. Say while a person is
behaving as a student it is sharing (inheriting) some attributes from person class. An employee could be
inheriting Name and ID properties and some methods from the person class as well, and so does a
manager, a customer and many more classes are specialized form of a person class.

When and why to use method over-riding?


 Use method over-riding in situation where you are dealing with (collection of) different behaviors of
classes inheriting from same base (parent) class and which role to act upon will be decided at run time.
 You should consider over-riding a method when you for some reason need a same interface (method)
for slightly different thing, that takes same parameters but give different output.

The following class diagram will shows that how we can use the feature of polymorphism with
inheritance.

Person Class
Properties
 ID
 FirstName
 LastName
Methods
 PrintFullName

Student Class
Employee Class
Properties
Properties
 TotalMarks
 AnnualSalary
 MarksObtained
Methods
Methods
 GetGrade
 GetMonthlySalary
 PrintFullName
 PrintFullName
Here the base class is Person and other two sub classes Employee and Student are inherited from it. Or we
can say Person can behave as an employee or student, but which one is not decided yet (at compile time).

You will get a better understanding if we see this action. Let's now incorporate these concept in our
inheritance code, done in previous labs.

Note: Our goal is to see polymorphism in action using inheritance and moving the common code from
child classes to the base class for better maintainability and reusability.

Step 1:
Let’s modify the code of our code as shown below.

1. Common
Field members

2. Base
Constructor
3. Common
Properties

4. Common
Virtual Method

Code Explanation:
1) Common fields are placed in base Person class and are marked as protected.
2) Base class constructor initializing the common fields.
3) Accessor properties for common fields.
4) Implementation of common method. Note that function is marked as virtual. A method or function of
the base class is available to the child (derived) class without the use of the "virtual" keyword. If it is
not a virtual method, it cannot be overridden but can be shadowed/hide.

Step 2:
Now let see how to use this Person base class to derive a more specialized Employee class.
Inheriting
from base
class

Derived Class
Constructor

Distinct Method

Now try executing the following main program as shown below.

Output:

Step 3:
Now try following changes in Employee class and observe the output.
Employee class
implementation of
PrintFullName( )
Function

From above snapshot it can be seen that there exists a warning, indicating either use new keyword or
override keyword. But for now we are going to ignore this warning, because we don’t what these keyword
implies here.
Output:
It is cleared from output below that Person’s implementation of PrintFullName( ) is executed when called
with Person’s object reference and Employee’s implementation of PrintFullName( ) is executed (by
hiding Person’s Function) when called with Employee’s object reference..

Now let’s make following changes to the main program and see if Person and Employee are polymorphic
or not?
Assigning Employee’s
instance to Person’s
object

Output:

It has been observed from the above output that in both cases base method is called, i.e. Person is not
behaving as Employee here.
Let’s try to remove existing warning by using the new keyword as shown below.

new keyword
added before
function signature
When we re-execute the program output remains same for both cases, i.e. base method is called. Still
Person is not behaving as Employee, i.e. they are not polymorphic.
Let’s try replacing the new keyword by override keyword as shown below and observe the output.

override keyword
added before
function signature

Output:
A strange thing happened here, Person’s implementation of PrintFullName( ) is executed when called
with Person’s object reference and Employee’s implementation of PrintFullName( ) is executed (by
overriding Person’s Function) even when called with Person’s object reference. Hence Person behaves as
an Employee here, i.e. it is polymorphic as shown in below output.

Similarly make another class where Person is behaving as Student, as shown in code below.
override keyword
added before
function signature

Now let see how to access these child classes from Program class in an interactive way.

1. Person Array
(Polymorph
Collection)

2. Run time
instance
selection

Code Explanation:
1) It can be seen from above code that a collection of Person is created and initialized with instances of
three morphed classes (i.e. Person, Employee and Student).
2) As you can see which instance will be selected is not known at compile time. User is provided with a
menu, from which it will select the behavior of Person at run-time. User will decide at run-time which
instance of polymorphic object will be picked and which instance of overridden PrintFullName( )
method will be called, all at run time.

Output:
You can see from the above output that Person behaves differently for different menu options.

Method Shadowing VS Method Overriding:

Shadowing Overriding
In hiding we can provide a new implementation Overriding allows us to re-write a base class
for the base class method without overriding it. function with a different definition.
Using the “new” keyword we can do the C# uses the “virtual/abstract” and override
shadowing or method hiding. keyword for method overriding.
Shadowing redefines an entire method or Overriding redefines only the implementation of
function. a method or function.
Showing is used to protect against subsequent Overriding does polymorphism by defining a
base class modification. different implementation.
We cannot change the access modifier. The access
We can change the access modifier. modifier must be the same as in the base class
method or function.
The base class has some control over the
There is no control of a base class on shadowing.
overriding. Using the keyword abstract, the base
In other words, a base class element cannot
class forces the child class to implement the
enforce or stop shadowing.
function or method.
Shadowing an element (function method or The same as shadowing, overriding an element is
property) can be inherited further in a child inherited further in a derived class and the
class. The shadowed element is still hidden. overridden element is still overridden.
In shadowing, the signature of an element could In overriding, the signature of the element must
be different. be the same.
In shadowing, the base class cannot access the In overriding, the base class can access the child
newly created child class method. This is (derived) class method by using child class
because the base class has the same name of instance. This is the beauty of polymorphism.
the element.

Advantages of Polymorphism:
It make possible to interact with a group of different classes through a common interface. This means
we can have a class that interacts with a lot of objects that all inherit from the same base class through the
methods that these objects share. The shared methods are known as the interface
Further, you cannot have runtime polymorphism without inheritance. So it has all the benefits to offer as
inheritance;
 It reduces code redundancy.
 It provides code reusability.
 Reduces source code size and improves code readability.
 After using this code is easy to manage and divided into parent and child classes.
 It supports code extensibility by overriding the base class functionality within child classes.

Disadvantage of Polymorphism:
Run time polymorphism makes performance issue as it needs to decide at run time so it degrade the
performance if there are lot of virtual functions.
Lab Task:
1) Create a base Shape class. Add constructors to it, non-parameterized, integer parameter. Add
properties to it. Add two sub-class Rectangle and Triangle. Base only shows SideA and SideB in
ShowDimension( ) method. For Triangle overrides ShowDimension( ) method to show SideC(along
with SideA and SideB). And GetArea( ) will have different implementation for Rectangle and
Triangle clesses.
Rectangle Class Triangle Class

 Properties  Properties
 SideA  SideA
 SideB  SideB
 Methods  SideC (Hypotenuse is Read-only)
 Rectangle( )  Methods
 Rectangle(SideA, SideB )  Triangle( )
 ShowDimension( )  Triangle(SideA, SideB)
 GetArea( )  ShowDimension( )
 GetPerimeter( )  GetArea( )

Home Task:
1) Make a MobilePhone base class with common code that will derives a CellPhone class and a
SmartPhone class. Add constructor and properties to it. Use single interface (polymorphism) to
access CellPhone and SmartPhone functions.

Smart Phone:
Cell Phone: - 3G/4G phone
- 2G phone - 6” display size
- 1.5” display size - Virtual Keyboard
- Physical Keyboard - Dual Camera
- T9 type keypad - Sophisticated Interface
- 2-way Navigation Keys - Audio Jack
- Simple Interface - Sensors
- Can Call - Can Call
- Can Text - Can Text
- Can make Tunes - Can Browse Internet
- Can Play Audio/Videos
- Can Download Apps
- Can Navigate Maps

You might also like