Polymorphism-

Definition – generally means “one name, many forms”
-in java, polymorphism means “one name of multiple methods, but different outputs.
Rule of polymorphism- method name must be same
 Types of polymorphism-
1- Compile time polymorphism/static method binding
2- Runtime polymorphism/dynamic method binding

1- Compile time polymorphism
-Calling method is decided at compile time
– In java, this is achieved by Method Overloading

(i) Method overloading
Rules of method overloading-
-only 1 class is required
-parameter must be different
-return type can be different or same

2- Runtime polymorphism
-Calling method is decided at runtime
-in java, this is achieved by method overriding

(ii) Method overriding
Rules of method overriding-
-at least 2 classes are required
-parameters must be same
-return type must be same

code samples are here

1- Compile time polymorphism


package polymorphism13;

public class ExampleCompilePoly {

void show(int a){
System.out.println("hello the number is "+a);
}

void show(String a){
System.out.println("hello the text is "+a);
}

public static void main(String[] args) {
ExampleCompilePoly e1=new ExampleCompilePoly();
e1.show(25); //will call first show method
}

}

 

2- Runtime polymorphism


package polymorphism13;

class A{
void display(){
System.out.println("hi");
}
}

public class ExampleRuntimePoly extends A {

void display(){
System.out.println("bye");
}
public static void main(String[] args) {

ExampleRuntimePoly n1 = new ExampleRuntimePoly();
n1.display(); //will call second display method
}
}

Advertisements