Understanding Java Polymorphism

In Java, polymorphism is the ability of a class to take on multiple forms. It allows objects of different classes to be treated as objects of a common base class. There are two types of polymorphism: compile-time (method overloading) and runtime (method overriding).

Compile-Time Polymorphism (Method Overloading):

Compile-time polymorphism is achieved through method overloading, where multiple methods in the same class have the same name but different parameter lists.


// Example of method overloading
public class Calculator {
  // Method with two int parameters
  public int add(int a, int b) {
    return a + b;
  }

  // Method with three int parameters
  public int add(int a, int b, int c) {
    return a + b + c;
  }
}

Runtime Polymorphism (Method Overriding):

Runtime polymorphism is achieved through method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.


// Example of method overriding
public class Animal {
  // Method in the superclass
  public void makeSound() {
    System.out.println("Generic animal sound");
  }
}

// Subclass that overrides the method
public class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow");
  }
}

Example:

Here's an example demonstrating the use of polymorphism in Java:


// Create objects of different types
Calculator calculator = new Calculator();
Animal genericAnimal = new Animal();
Animal cat = new Cat();

// Compile-time polymorphism (method overloading)
int result1 = calculator.add(2, 3);
int result2 = calculator.add(2, 3, 4);

// Runtime polymorphism (method overriding)
genericAnimal.makeSound(); // Output: Generic animal sound
cat.makeSound(); // Output: Meow

Note:

Polymorphism in Java allows for flexibility and extensibility in designing classes. Method overloading and method overriding are two essential concepts that contribute to achieving polymorphism in Java.