Junior
What should differentiate two methods for them to be considered overloaded?
sobes.tech AI
Answer from AI
For two methods to be considered overloaded, they must meet the following conditions:
- Same method name. The method names must be identical.
- Different method signatures. The method signature includes the method name and the list of parameter types (their number, order, and types). The return type of the method is not part of the signature and does not affect overloading.
Examples:
class Example {
void print(int num) { // Signature: print(int)
System.out.println(num);
}
void print(String text) { // Signature: print(String)
System.out.println(text);
}
void print(int num, String text) { // Signature: print(int, String)
System.out.println(num + " " + text);
}
// This is not overloading because the signature print(int) repeats
// int print(int num) {
// return num;
// }
}
The table illustrating examples of overloading:
| Method Name | Parameter Types | Same / Different Methods | Is Overloading? | Reason |
|---|---|---|---|---|
calc |
(int, int) |
Different | Yes | Different signature (number and types of parameters) |
calc |
(double, double) |
Different | Yes | Different signature (parameter types) |
calc |
(int, int, int) |
Different | Yes | Different signature (number of parameters) |
calc |
() |
Different | Yes | Different signature (number of parameters) |
calc |
(int, int) |
Same | No | Same signature |
calculate |
(int, int) |
Different | No | Different method name |