Table of Contents

Polymorphism in Java

Definition:

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) that allows methods to do different things based on the object it is acting upon. It means "many forms" and it allows one interface to be used for a general class of actions. The specific action is determined by the exact nature of the situation.

Polymorphism in Java is broadly categorized into two types:

  1. Compile-Time Polymorphism (Static Polymorphism)
  2. Runtime Polymorphism (Dynamic Polymorphism)

1. Compile-Time Polymorphism

Compile-time polymorphism is achieved through method overloading. It is resolved during the compile time.

Method Overloading:

Method overloading is a feature that allows a class to have more than one method having the same name, if their parameter lists are different. It is related to compile-time (or static) polymorphism.

Example:

class MathOperations {
    // Method with two integer parameters
    int add(int a, int b) {
        return a + b;
    }

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

    // Method with two double parameters
    double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        MathOperations math = new MathOperations();
        System.out.println("Addition of two integers: " + math.add(5, 10)); // Calls method with two int parameters
        System.out.println("Addition of three integers: " + math.add(5, 10, 15)); // Calls method with three int parameters
        System.out.println("Addition of two doubles: " + math.add(5.5, 10.5)); // Calls method with two double parameters
    }
}

Output:

Addition of two integers: 15
Addition of three integers: 30
Addition of two doubles: 16.0

In this example, the add method is overloaded with different parameter lists. The appropriate method is called based on the arguments passed.

Method Overload Resolution

Definition:

Method overload resolution is the process by which the Java compiler determines which method to call when multiple methods with the same name but different parameters exist in a class. The decision is based on the method signature, which includes the number, type, and order of parameters.