Difference between compile-time polymorphism and runtime polymorphism

JavaServer Side ProgrammingProgramming

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.KeyCompile-time polymorphismRuntime 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/Dynamic
Binding


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");
   }
}
raja
Published on 09-Sep-2020 12:00:06
Advertisements