Skip to content

Polymorphism

Polymorphism in Java is one of the key principles of object-oriented programming (OOP). It allows objects to take multiple forms depending on the context. In simpler terms, polymorphism enables a single interface to represent different underlying forms (data types).

Types of Polymorphism in Java:

  1. Compile-time Polymorphism (Method Overloading): Achieved by defining multiple methods with the same name but different parameter lists in the same class.
  2. Runtime Polymorphism (Method Overriding): Achieved when a subclass provides a specific implementation for a method that is already defined in its superclass.

1. Compile-Time Polymorphism (Method Overloading):

This is resolved during compilation.

Example:

class Calculator {

    // Method to add two integers

    int add(int a, int b) {

        return a + b;

    }

    // Method to add three integers

    int add(int a, int b, int c) {

        return a + b + c;

    }

    // Method to add two double values

    double add(double a, double b) {

        return a + b;

    }

}

public class Main {

    public static void main(String[] args) {

        Calculator calc = new Calculator();

        // Calling the overloaded methods

        System.out.println(“Sum of 2 integers: ” + calc.add(10, 20));

        System.out.println(“Sum of 3 integers: ” + calc.add(10, 20, 30));

        System.out.println(“Sum of 2 doubles: ” + calc.add(10.5, 20.5));

    }

}

Output:

Sum of 2 integers: 30

Sum of 3 integers: 60

Sum of 2 doubles: 31.0


2. Runtime Polymorphism (Method Overriding):

This is resolved during runtime.

Example:

class Animal {

    // Method to be overridden

    void sound() {

        System.out.println(“Animal makes a sound”);

    }

}

class Dog extends Animal {

    // Overriding the sound method

    @Override

    void sound() {

        System.out.println(“Dog barks”);

    }

}

class Cat extends Animal {

    // Overriding the sound method

    @Override

    void sound() {

        System.out.println(“Cat meows”);

    }

}

public class Main {

    public static void main(String[] args) {

        Animal myAnimal;

        // Reference of Animal pointing to Dog object

        myAnimal = new Dog();

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

        // Reference of Animal pointing to Cat object

        myAnimal = new Cat();

        myAnimal.sound();  // Output: Cat meows

    }

}

Explanation:

  • Parent class reference (Animal) can hold an object of a subclass (Dog or Cat).
  • The actual method invoked depends on the runtime object type.

Output:

Dog barks

Cat meows


Key Points to Remember:

  • Overloading is an example of compile-time polymorphism (method resolution happens at compile time).
  • Overriding is an example of runtime polymorphism (method resolution happens at runtime).
  • Polymorphism improves code reusability and flexibility, enabling developers to write more dynamic and scalable programs.