polymorphism


Polymorphism
Def: --- Polymorphism is a concept of having many functions or methods with same name but with different no of parameters in a  class.     
Polymorphism is of two types.
1. Static Polymorphism     2. Dynamic Polymorphism .
1. Static Polymorphism or compile time polymorphism :-
It is achieved through the concept of Overloading technique and also binding (Binding means, the code is available to its related function calls. )
Method Overloading
Method overloading means creating a new method with the same name and different signature. It uses compiletime binding. Two or more methods in a Java class can have the same name, if their argument lists are different, the feature is known as Method Overloading. Argument list could differ in no of parameters, data type of parameters, sequence of parameters. Calls to overloaded methods will be resolved during compile time. Method overloading is nothing but a Static Polymorphism.
Example:
/*in static polymorphism at compile time and runtime it calls same method  definition */
class polyEx {
void area() {
int l=3,b=4;
System.out.println("rectangle area is:"+(l*b));
}
int area(int a) {
System.out.println("square area is:"+(a*a));
return(a*a);
}
polyEx area(int b,int h) {
System.out.println("triangle area is:"+(0.5*(b*h)));
return new polyEx();
}
public static void main(String  [] args) {
System.out.println("main started");
polyEx p= new polyEx();
p.area();
int ar=new polyEx().area(3);
p.area(4,5);
System.out.println("main ended");
}
}
2. Runtime Polymorphism or dynamic Polymorphism :--achieved through overriding.
Method Overriding
when the super class method not satisfying the subclass requirements then the subclass can also redefine the same method according to its requirements this is known as Method overriding  .
class Super {
void area(int x){
System.out.println("\nSuper class area method");
}
}
class RunPolyDemo extends Super{
void area(int a){
System.out.println("area of square is: "+(a*a));
}
public static void main(String args[]){
Super    d = new RunPolyDemo();
d.area(3);
}
}
Note: - This runtime polymorphism is achieved by storing sub-class object reference in superclass  object reference variable.In this case the method call will bind with one method(super class) at compiletime and will bind with the other method(sub-class) at runtime.

No comments:

Post a Comment