How does method overloading relate to polymorphism?

Method overloading is a form of Compile-Time Polymorphism in Java. It allows multiple methods within the same class to have the same name but different parameter lists. The compiler determines which method to execute based on the number, type, or order of arguments passed.

Key Points: • Method overloading is an example of Compile-Time (Static) Polymorphism. • Multiple methods can share the same name as long as their parameters differ. • The method to be executed is determined during compilation. • Overloading improves code readability by allowing related operations to use a common method name. • Return type alone cannot be used to overload a method.

Example: A calculator may use the same add() method name to add integers, doubles, or multiple values. Although the method name remains the same, Java selects the appropriate method based on the arguments provided.

Code Example:

class Calculator {

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

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

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

public class Demo {

    public static void main(String[] args) {

        Calculator calc = new Calculator();

        System.out.println(calc.add(10, 20));
        System.out.println(calc.add(10.5, 20.5));
        System.out.println(calc.add(10, 20, 30));
    }
}

Output:

30
31.0
60

How It Relates to Polymorphism:

• One method name represents multiple behaviors. • The same method call can perform different operations based on the arguments passed. • The compiler resolves the appropriate method at compile time. • This flexibility is why method overloading is considered a type of polymorphism.

Interview Tip: A concise interview answer is:

"Method overloading is a form of compile-time polymorphism where multiple methods in the same class share the same name but have different parameter lists. The compiler determines which method to invoke based on the arguments provided, allowing one method name to perform multiple related operations."