Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Method overloading

Method overloading lets several methods share a name while using different parameter lists. The compiler selects an overload using the arguments and their compile-time types, rather than the runtime classes of argument objects.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

static String describe(int value) { return "int"; }
static String describe(Object value) { return "Object"; }
static String describe(String value) { return "String"; }

Method overloading occurs when methods belonging to a class share a name but have signatures that are not override-equivalent. These methods may be declared in that class or inherited.

For ordinary non-generic methods, overloads differ in the number, types, or order of parameter types. Parameter names, the return type, or the throws clause alone cannot create an overload.

Overload selection happens at compile time. In the example, describe(value) selects describe(Object) because the declared type of value is Object, even though it holds a String object. Do not confuse this with overriding: for a selected instance-method signature, the implementation may be determined at runtime.

If no method is applicable, or a most-specific method cannot be selected unambiguously, compilation fails. Overloads should represent the same operation for different inputs so that calls remain easy to understand.

Examples

public class Main {
    static String describe(int value) {
        return "int";
    }

    static String describe(Object value) {
        return "Object";
    }

    static String describe(String value) {
        return "String";
    }

    public static void main(String[] args) {
        Object value = "hello";
        System.out.println(describe(7));
        System.out.println(describe("hello"));
        System.out.println(describe(value));
    }
}

Result

int
String
Object

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources