Polymorphism in Java

What is Polymorphism?

Polymorphism means “many forms.” In Java, it allows an object to take multiple forms. It is one of the four main OOP (Object-Oriented Programming) concepts, along with inheritance, encapsulation, and abstraction.

Polymorphism in Java occurs in two main types:

  1. Compile-time Polymorphism (Method Overloading)
    • Happens at compile time.
    • Achieved by method overloading (same method name, different parameters).
  2. Run-time Polymorphism (Method Overriding)
    • Happens at runtime.
    • Achieved by method overriding (subclass provides a specific implementation of a method already defined in the parent class).

Example of Compile-time Polymorphism (Method Overloading)

class Calculator {
    // Add two integers
    int add(int a, int b) {
        return a + b;
    }

    // Add three integers
    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10));       // Output: 15
        System.out.println(calc.add(5, 10, 15));   // Output: 30
    }
}

✅ Here, the add method behaves differently depending on the number of arguments.


Example of Run-time Polymorphism (Method Overriding)

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

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

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

public class Main {
    public static void main(String[] args) {
        Animal myAnimal;

        myAnimal = new Dog();
        myAnimal.sound();  // Output: Dog barks

        myAnimal = new Cat();
        myAnimal.sound();  // Output: Cat meows
    }
}

✅ Here, the same reference type (Animal) behaves differently depending on the object it refers to at runtime. This is runtime polymorphism.


Key Points

  • Polymorphism improves code flexibility and reusability.
  • Compile-time polymorphism → Method overloading
  • Run-time polymorphism → Method overriding
  • Achieved mainly through inheritance and interfaces.

Leave a Reply