Method overloading

Several methods can share a name if their parameter lists differ. The compiler picks one from the argument types.

Time resolved at compile timeSpace O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Overload choice happens when the code is compiled, using the declared types of the arguments. That is the opposite of overriding, where the choice is made at run time from the real object.

Code

var p = new Printer();
p.Print(5);
p.Print(2.5);
p.Print("hi");
object boxed = 5;
p.Print(boxed);   // chosen by the variable's type, not the value inside

class Printer {
    public void Print(int x) => Console.WriteLine("int " + x);
    public void Print(double x) => Console.WriteLine("double " + x);
    public void Print(string x) => Console.WriteLine("string " + x);
    public void Print(object x) => Console.WriteLine("object " + x);
}
class Printer {
    public void print(int x) { System.out.println("int " + x); }
    public void print(double x) { System.out.println("double " + x); }
    public void print(String x) { System.out.println("string " + x); }
    public void print(Object x) { System.out.println("object " + x); }
}

public class Main {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.print(5);
        p.print(2.5);
        p.print("hi");
        Object boxed = 5;
        p.print(boxed);   // chosen by the variable's type, not the value inside
    }
}
class Printer {
public:
    void print(int x) { cout << "int " << x << "\n"; }
    void print(double x) { cout << "double " << x << "\n"; }
    void print(const string& x) { cout << "string " << x << "\n"; }
    void print(const any& x) { cout << "object of type " << x.type().name() << "\n"; }
};

int main() {
    Printer p;
    p.print(5);
    p.print(2.5);
    p.print("hi"s);
    any boxed = 5;
    p.print(boxed);   // chosen by the variable's type, not the value inside
}
from functools import singledispatchmethod

class Printer:  # Python has no overloading: singledispatch picks by runtime type
    @singledispatchmethod
    def show(self, x: object) -> None: print("object", x)

    @show.register
    def _(self, x: int) -> None: print("int", x)

    @show.register
    def _(self, x: float) -> None: print("float", x)

    @show.register
    def _(self, x: str) -> None: print("string", x)

p = Printer()
p.show(5)
p.show(2.5)
p.show("hi")
boxed: object = 5
p.show(boxed)  # dispatch uses the value's runtime type: prints "int 5"

Tips

In the .NET library

Console.WriteLine itself has 18 overloads. Optional parameters (int retries = 3) often replace a pile of overloads.