Card 07/ 10
All 10 cards
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.
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; }| Difference | Enough to overload? |
|---|---|
| Number of parameters | Yes |
| Types of parameters | Yes |
| Order of parameter types | Yes, when the types differ |
| Return type | No |
| Parameter names | No |
| Access modifier | No |
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.