Polymorphism:
- Poly means many and prism means form so polymorphism means many forms.
- It is used to perform a single action in different ways.
- For example,
- Action is drawn and it performance maybe draw a line or draw a circle.
Types of polymorphism:
1. Runtime polymorphism
2. Compile time polymorphism
Runtime polymorphism:
- The runtime polymorphism is also called dynamic polymorphism.
- It is the best example is method overloading.
Example program:
#include<iostream.h>
#include<conio.h>
class Shape {
public:
double a;
void area() {
cout<<"\n\tCalculating
area of Rectangle,Circle,Triangle .........";
}
};
class Rectangle: public Shape {
public:
void area() {
float
l,w;
cout<<"\n\nEnter
length and width of rectangle : ";
cin>>l>>w;
a=l*w;
//area=length*width;
cout<<"\nArea
of rectangle : "<<a;
}
};
class Circle:public Shape {
public:
void area() {
float
r;
cout<<"\n\nEnter
radius of circle : ";
cin>>r;
a=3.14*r*r;
//area=3.14*radius*radius;
cout<<"\nArea
of circle : "<<a;
}
};
void main()
{
clrscr();
Shape
s;
s.area();
Rectangle
r;
r.area();
Circle
c;
c.area();
getch();
}
Output:
Compile-time polymorphism:
- The runtime polymorphism is also called static polymorphism.
- It is the best example is method overriding.
Example program:
#include<iostream.h>
#include<conio.h>
class Shape {
public:
double a;
void area() {
cout<<"\n\tCalculating area of Rectangle,Circle,Triangle .........";
}
};
class Rectangle:public Shape {
public:
void area(float l,float w) {
//float l,w;
cout<<"\n\nEnter length and width of rectangle : ";
cin>>l>>w;
a=l*w; //area=length*width;
cout<<"\nArea of rectangle : "<<a;
}
};
class Circle:public Shape {
public:
void area(float r) {
//float r;
cout<<"\n\nEnter radius of circle : ";
cin>>r;
a=3.14*r*r; //area=3.14*radius*radius;
cout<<"\nArea of circle : "<<a;
}
};
void main()
{
clrscr();
Shape s;
s.area();
Rectangle r;
r.area(6,3);
Circle c;
c.area(3.2);
getch();
}
Output:
No comments:
Post a Comment