Skip to content

Method Overloading

Method overloading is a feature that allows a class to have multiple methods with the same name but different parameters (different number or types of parameters). It’s a form of compile-time polymorphism.

  • To provide convenience — different ways to call the same operation
  • To make code more intuitive — same operation, different inputs
  • To implement compile-time polymorphism (static polymorphism)

“Order coffee” could mean:

  • order() — Just coffee (default)
  • order("Latte") — Specify type
  • order("Latte", "Large") — Type and size
  • order("Latte", "Large", "Oat Milk") — Type, size, and milk

Same operation, different ways to call it. That’s overloading.


Method overloading is defining multiple methods with the same name in the same class, but with different parameter lists (different number, type, or order of parameters).


class Calculator {
add(a, b, c) {
if (c !== undefined) return a + b + c;
return a + b;
}
format(input) {
if (typeof input === "number") return input.toFixed(2);
if (typeof input === "string") return input.trim();
return String(input);
}
sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
}

Overloading = Same name, different parameters (compile-time)
Overriding = Child redefines parent method (run-time)


Previous Topic: Polymorphism Overview → Next Topic: Object Relationships →