Difference Between Compile-Time 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
Updated on: 2019-07-30T22:30:20+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements