Card 07/ 10

ComparisonDifficulty: Intermediate1 min

What Overloading Resolves On, and What It Ignores

Two methods with the same name in one class is legal and useful. Two methods with the same name and the same parameter list is a compile error, even if everything else about them differs.

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 modifierNo

Only the parameter list counts, which is worth pairing 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.