Polymorphism is the ability to take more than one form. It means you can perform single action using multiple ways. There are two types of polymorphism:

  • Compile time Polymorphism (Method Overloading)
  • Run time Polymorphism (Method Overriding)

 
1. Compile time Polymorphism (Method Overloading) – The ability to execute the methods which have same name with different arguments are known as method overloading.
Example:

public class Intellipaat{
public void sample(int a){
System.out.println(a);
}
public void sample(String s){
System.out.println(s);
}
public void sample(int a, int b){
System.out.println((a + b));
}
public static void main(String []args){
Intellipaat i = new Intellipaat ();
i.sample(20);
i.sample("intellipaat");
i.sample(10, 20);
}
}

Output
10
intellipaat
30
 
2. Run time Polymorphism (Method Overriding) – The ability to execute the method which have same name with same arguments is known as method overriding. It is a process in which a call to an overridden method is determined at runtime rather than compile-time. When reference variable of Parent class refers to the object of Child class then it is known as upcasting.
In method overriding case both classes contain same method so it is  unknown that which method is executed so in this condition JVM decides which method to call at runtime so that’s why it is known as run time polymorphism.
Example

class A
{
public void sample() //Base class method
{
System.out.println ("Class A method");
}
}
public class B extends A
{
public void sample() //Derived Class method
{
System.out.println ("Class B method ");
}
public static void main (String args []) {
A ob1 = new A(); // Reference and object A
A ob2 = new B(); // A reference but B object(upcasting)
B ob3 = new B(); // Reference and object B
ob1.sample();
ob2.sample();
ob3.sample();
}
}

Output
Class A method
Class B method
Class B method
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
9 ⁄ 3 =