Difference between compile-time polymorphism and runtime polymorphism



Polymorphism is one of the most important OOPs concepts. Its is a concept by which we can perform single task in multiple ways. There are two types of polymorphism one is Compile-time polymorphism and another is run-time polymorphism.

Method overloading is the example of compile time polymorphism and  method overriding is the example of run-time polymorphism.

Sr. No. Key Compile-time polymorphism Runtime polymorphism
1 Basic Compile time polymorphism means binding is occuring at compile time R un time polymorphism where at run time we came to know which method is going to invoke
2 Static/DynamicBinding It can be achieved through static binding It can be achieved through dynamic binding
4. Inheritance Inheritance is not involved Inheritance is involved
5 Example Method overloading is  an example of compile time polymorphism Method overriding is an example of runtime polymorphism

Example of Compile-time Polymorphism

public class Main {
   public static void main(String args[]) {
      CompileTimePloymorphismExample obj = new CompileTimePloymorphismExample();
      obj.display();
      obj.display("Polymorphism");
   }
}
class CompileTimePloymorphismExample {
   void display() {
      System.out.println("In Display without parameter");
   }
   void display(String value) {
      System.out.println("In Display with parameter" + value);
   }
}

Example of Runtime Polymorphism

public class Main {
   public static void main(String args[]) {
      RunTimePolymorphismParentClassExample obj = new RunTimePolymorphismSubClassExample();
      obj.display();
   }
}

class RunTimePolymorphismParentClassExample {
   public void display() {
      System.out.println("Overridden Method");
   }
}

public class RunTimePolymorphismSubClassExample extends RunTimePolymorphismParentExample {

   public void display() {
      System.out.println("Overriding Method");
   }
}
Updated on: 2023-09-12T09:54:51+05:30

36K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements