Polymorphism:
- Ploy means many
and prism means form so polymorphism means many form.
- It is used to
perform a single action in different ways.
- For example,
- Action is draw
and it performance may be draw a line or draw circle.
Types of polymorphism:
1. Runtime polymorphism
2. Compile time polymorphism
Runtime polymorphism:
- The runtime polymorphism
is also called as dynamic polymorphism.
- It is best
example is method overloading.
Example program:
import
java.util.Scanner;
class Shape {
Scanner sc = new
Scanner(System.in);
double a;
void area() {
System.out.println("\tCalculating
area of Rectangle,Circle,Triangle .........");
}
}
class Rectangle
extends Shape {
void area() {
float l,w;
System.out.println("Enter length
and width of rectangle : ");
l=sc.nextFloat();
w=sc.nextFloat();
a=l*w; //area=length*width;
System.out.println("Area of
rectangle : "+a);
}
}
class Circle
extends Shape {
void area() {
float r;
System.out.println("Enter
radius of circle : ");
r=sc.nextFloat();
a=3.14*r*r; //area=3.14*radius*radius;
System.out.println("Area of circle
: "+a);
}
}
class Triangle
extends Shape {
void area() {
double b,h;
System.out.println("Enter base and
length of triangle : ");
b=sc.nextDouble();
h=sc.nextDouble();
a=(b*h)/2; //area=1/2*Base*length;
System.out.println("Area of
triangle : "+a);
}
}
class
Runtime_Polymerpism {
public static void main(String args[]) {
Shape s=new Shape();
s.area();
s = new Rectangle();
s.area();
s = new Circle();
s.area();
s = new Triangle();
s.area();
}
}
Output:
Compile time polymorphism:
- The runtime polymorphism
is also called as static polymorphism.
- It is best
example is method overriding.
Example program:
public class
Complietime_polymorpism {
float l, w, r;
double a,b, h;
void area() {
System.out.println("\tCalculating
area of Rectangle,Circle,Triangle .........");
}
void area(float l, float w) {
a = l * w; //area=length*width;
System.out.println("Area of
rectangle : " + a);
}
void area(float r) {
a = 3.14 * r * r;
//area=3.14*radius*radius;
System.out.println("Area of circle
: " + a);
}
void area(double b, double h) {
a = (b * h) / 2;
//area=1/2*Base*length;
System.out.println("Area of
triangle : " + a);
}
}
class
Passing_value_through_obj {
public static void main(String args[]) {
Complietime_polymorpism cp = new
Complietime_polymorpism();
cp.area();
cp.area(1, 2);
cp.area(2);
cp.area(8, 5);
}
}
Output:
No comments:
Post a Comment