What is the difference between compile time polymorphism and runtime polymorphism in java?



If we perform (achieve) method overriding and method overloading using instance methods, it is run time (dynamic) polymorphism.

In dynamic polymorphism the binding between the method call an the method body happens at the time of execution and, this binding is known as dynamic binding or late binding.

Example

Live Demo

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class RuntimePolymorphism extends SuperClass {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass obj1 = new RuntimePolymorphism();
      RuntimePolymorphism obj2 = new RuntimePolymorphism();
      obj1.sample();
      obj2.sample();
   }
}

Output

Method of the super class
Method of the sub class

If we perform (achieve) method overriding and method overloading using static, private, final methods, it is compile time (static) polymorphism.

In static polymorphism the binding between the method call an the method body happens at the time of compilation and, this binding is known as static binding or early binding.

Example

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class SubClass extends SuperClas {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass.sample();
      SubClass.sample();
   }
}

Output

Method of the super class
Method of the sub class

Advertisements