Polymorphism

Polymorphism is a fundamental concept in object-oriented programming, and it plays a crucial role in Java. It allows you to write code that can work with objects of different classes in a consistent manner.

There are two types of polymorphism in Java: compile-time (static) polymorphism and runtime (dynamic) polymorphism.

1. Compile-time (Static) Polymorphism:

This type of polymorphism is also known as method overloading.

  • It occurs when multiple methods in the same class have the same name but different parameter lists (number or types of parameters).

  • The appropriate method to execute is determined at compile time based on the method signature and the arguments passed.

class MathOperations {
    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) {
        MathOperations math = new MathOperations();
        int sum1 = math.add(2, 3);
        double sum2 = math.add(2.5, 3.7);
        System.out.println("Sum1: " + sum1);
        System.out.println("Sum2: " + sum2);
    }
}

In this example, the add method is overloaded with two versions, one that accepts integers and another that accepts doubles. The appropriate method is called based on the argument types during compile time.

2. Runtime (Dynamic) Polymorphism:

This type of polymorphism is also known as method overriding.

  • It occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

  • The determination of which method to execute is made at runtime based on the actual type of the object.

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

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

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog(); // Polymorphic reference
        myAnimal.makeSound(); // Calls the overridden method in Dog
    }
}

In this example, the makeSound method is overridden in the Dog class. Even though we have a reference of the superclass Animal, when we call makeSound() on the myAnimal object, it executes the overridden method in the Dog class because the actual type of the object is a Dog.

Polymorphism is a powerful feature in Java that allows for flexibility and extensibility in your code, making it easier to work with different classes and hierarchies of objects in a unified way. It's a fundamental principle of object-oriented programming and is widely used in Java applications.

Last updated