Friday, January 14, 2011

Polymorphism

Polymorphism
Polymorphism means having many shapes. Polymorphism allows improved code organization and readability. Its ability of an object is to respond differently to the same message. When a message is send to an object even though we don’t know what specific type it is, but the right thing happens, that’s called polymorphism.

Types of Polymorphism
  • Compile-time polymorphism (early binding)
  • Compile-time polymorphism is also called method overloading.

Compile-Time Polymorphism
Compile-time or Early binding is achieved by Overloading which allows us to have two or more methods in the same class have the same name with different parameters

Example:
We will create a method that will calculate the square of a given number having same name but different data type.


In this program we have use different methods having same name but different parameters this is called overloading.

Run-time polymorphism

Run-time polymorphism is achieved by method overriding.
Overriding allows us to have methods in the base and derived classes with same name and same parameters.

Example:
We have created three classes clsLine, clsTriangle, clsCircle derived from base class clsShapes. clsShapes contain draw() method and clsTriangle and clsCircle contains fill() method. We have declared draw() method as virtual method(virtual keyword is use to modify properties and allow method to be overridden ) so we can override that method  in derived classes by modifying implementation of virtual method with respect to derived classes. So the method to be executed is selected dynamically during run-time.


Now make an object 
clsShapes objShape = new clsTriangle();
and call method draw().


In this picture objShape.draw() is called and you can see the result it says "draw from clsTriangle" which means that draw method is called from clsTriangle class. We can determine the result when we run this program but not on compile-time.

No comments:

Post a Comment