Compile-time vs. Run-time Polymorphism in Object Oriented Programming

There are two main types of polymorphism in object-oriented programming. These are compile-time polymorphism and Run-time polymorphism.

Compile-time Polymorphism

Compile time polymorphism is a type of polymorphism occurring when the method call gets resolved during compile time, whereas compile time polymorphism is achieved with the help of method overloading and operator overloading.

In method overloading, we use the same methods with different parameters to achieve polymorphism. We do not need to keep different names for the same function. This improves the effectiveness of the code. It is also known as Static binding or early binding (as opposed to dynamic binding).

Let us suppose we need to multiply two different numbers, and we can write a function named multiply to achieve this. However, if we need to multiply three numbers, then with the help of polymorphism in OOP, we do not need to write the complete code again.

// ...
  public int multiply(int a, int b)    {
      int prod = a * b;
      return prod;
  }

  public int multiply(int a, int b, int c)
  {
      int prod = a * b * c;
      return prod;
  }

}

// Class 2

// Main class

class Operation {
  // Main driver method
  public static void main(String[] args)
  {
      Product ob = new Product();
      int prod1 = ob.multiply(1, 2);s
      System.out.println(
          "Product of the two integer value :" + prod1);

      // Calling method to multiply 3 numbers
      int prod2 = ob.multiply(1, 2, 3);

      // Printing product of 3 numbers
      System.out.println(
          "Product of the three integer value:" + prod2);
  }
}

Here, we are using multiply(int a, int b) for two-digit multiplication. For three-digit multiplication, we call the method with the same name but a different parameter.

Run-time Polymorphism

Run-time polymorphism is a type of polymorphism in OOPS which is resolved during runtime. This is generally achieved with the help of method overriding. Method overriding is used to implement a method that is already defined in its parent class or super class. Runtime polymorphism in OOP is also known as dynamic binding or late binding.

Let us understand runtime polymorphism with the help of an example.

In this example, the sound method, which is already defined in the Animal class, is overridden and used in the Dog class. When this sound method is called for a dog object, it will print "Dog barks".