Compile-Time Polymorphism

Method Overloading

Several methods with the same name but different parameter lists (number, type or order). The return type alone cannot distinguish overloads.

Example

public class Main {
    static int add(int a, int b) {
        return a + b;
    }

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

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

    static String add(String a, String b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(2, 3));
        System.out.println(add(2.5, 3.1));
        System.out.println(add(1, 2, 3));
        System.out.println(add("Care", "eroza"));
    }
}

Output

5
5.6
6
Careeroza

Which Overload Wins?

Example

The compiler picks the most specific match. An exact match beats widening (int → long), which beats boxing (int → Integer), which beats varargs.

public class Main {
    static void show(long x)      { System.out.println("long"); }
    static void show(Integer x)   { System.out.println("Integer"); }
    static void show(int... x)    { System.out.println("varargs"); }
    static void show(Object x)    { System.out.println("Object"); }

    public static void main(String[] args) {
        int n = 5;
        show(n);          // widening to long wins over boxing
        show("hi");       // only Object matches
        show();           // only varargs matches
        Integer boxed = 7;
        show(boxed);      // exact match
    }
}

Output

long
Object
varargs
Integer