Method overloading means defining multiple methods with the same name but different parameter lists (different number, types, or order of parameters) within the same class. The correct version to call is chosen automatically based on the arguments provided — this is compile-time polymorphism, introduced in the Polymorphism chapter.
class Printer {
function print(string text) {
output(text)
}
function print(string text, int copies) {
for i in range(copies):
output(text)
}
function print(int[] numbers) {
output(join(numbers, ", "))
}
}
printer.print("Hello") // calls version 1
printer.print("Hello", 3) // calls version 2, prints 3 times
printer.print([1, 2, 3]) // calls version 3
Overriding vs. overloading — a common point of confusion:
| Overriding | Overloading | |
|---|---|---|
| Where | Between a parent class and subclass | Within the same class |
| Signature | Must be identical to the parent's | Must differ (parameters) |
| Resolved | At runtime, based on actual object type | At compile time, based on arguments |
| Purpose | Customize inherited behavior | Provide convenient variations of one operation |
Language support varies: Java, C++, and C# support true method overloading natively. PHP, Python, and JavaScript do not — defining two methods with the same name in the same class simply makes the second definition silently replace the first. These languages instead achieve similar flexibility using default parameter values, variadic parameters (...args), or manual type-checking with a single method (instanceof checks or match/switch on argument type inside the function body).