Java - OOP - Polymorphism

Java Polymorphism is the ability of an object to take on multiple forms. In other words, it allows us to perform a single action in different ways. In Java, there are two types of polymorphism: compile-time polymorphism (or method overloading) and runtime polymorphism (or method overriding).

Method Overloading:

Method overloading is a type of compile-time polymorphism where we can define multiple methods with the same name in the same class. The methods must have different method parameters or arguments. This means that the methods have the same name but different input parameters.

In the above example, we have defined two methods with the same name "add". The first method takes two integer parameters, and the second method takes three integer parameters. Both methods have different implementations, but they have the same name. When we call the add method, Java decides which method to call based on the number and types of arguments.

public class Calculator {
   public int add(int num1, int num2) {
      return num1 + num2;
   }
   public int add(int num1, int num2, int num3) {
      return num1 + num2 + num3;
   }
}

Method Overriding:

Method overriding is a type of runtime polymorphism where we can define a method in a subclass that already exists in the parent class. The method in the subclass should have the same name, return type, and arguments as the method in the parent class.

public class Animal {
   public void makeSound() {
      System.out.println("Animal is making a sound.");
   }
}

public class Dog extends Animal {
   public void makeSound() {
      System.out.println("Dog is barking.");
   }
}

In the above example, the Dog class is a subclass of the Animal class. The Dog class overrides the makeSound() method of the Animal class. When we call the makeSound() method for a Dog object, it calls the overridden method in the Dog class.

Polymorphism allows us to write flexible and reusable code. By using polymorphism, we can write code that can work with objects of different classes without knowing the exact class of the object.