Polymorphism is a core concept in Object-Oriented Programming (OOP) that allows objects to take multiple forms. It enables a single interface or method to work differently based on the object or data type it operates on. This makes code more flexible, reusable, and easier to maintain.

Types of Polymorphism

Polymorphism in Java can be classified into two main types:

1. Compile-Time Polymorphism (Static Polymorphism)

This occurs when the method to be called is determined at compile time. It is achieved through method overloading or operator overloading (though Java doesn’t support operator overloading).

Method Overloading: Defining multiple methods with the same name but different parameter lists (number or type of parameters).

Example:

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    
    double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10)); // Calls add(int, int)
        System.out.println(calc.add(5.5, 2.5)); // Calls add(double, double)
    }
}

Key Points:

  • Method overloading improves readability and usability.
  • Resolved during compilation.

2. Runtime Polymorphism (Dynamic Polymorphism)

This occurs when the method to be executed is determined at runtime. It is achieved through method overriding.

Method Overriding: When a subclass provides a specific implementation for a method that is already defined in its parent class.

Example:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog(); // Upcasting
        myAnimal.sound(); // Calls Dog's sound method
    }
}

Key Points:

  • Requires inheritance.
  • Achieved using method overriding.
  • Resolved during runtime.

Interview Questions

  1. What is polymorphism in Java?

  2. Differentiate between method overloading and overriding.

  3. How does the JVM resolve method calls in runtime polymorphism?

  4. Why is method overriding necessary for runtime polymorphism?

  5. Can we override static methods in Java? (Hint: No, because static methods belong to the class, not instances).