Card 07/ 10
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:
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 (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.
← → move through sections and cards