Card 07/ 10

ComparisonDifficulty: Intermediate1 min

Method Overloading: What the Compiler Matches On

Same name, different parameter lists: legal. Same parameters, different return types: a compile error.

Overloading is declaring several methods with the same name in one class. It is allowed only when their parameter lists differ in number, type or order of types; the compiler picks one by matching the arguments at the call, and ignores the return type and parameter names.

Three methods called area, one per shape:

java
int area(int side) { return side * side; }
int area(int width, int height) { return width * height; }
double area(double radius) { return Math.PI * radius * radius; }
What the compiler uses to tell two same-named methods apart
DifferenceEnough to overload?
Number of parametersYes
Types of parametersYes
Order of parameter typesYes, when the types differ
Return typeNo
Parameter namesNo
Access modifier (public, private and so on)No

Only the parameter list counts, which pairs with a fact from reading a signature: the return type is not part of what a call matches. int read() and String read() in one class do not compile, because nothing at the call site would say which you meant.

The decision rule. Overload when the same idea takes different inputs: area of a square, a rectangle, a circle. Do not overload when the methods do different things, because a reader choosing between them has only the argument types to go on, and those do not say what will happen.