Java Reference
In-Depth Information
The rules that apply to method overloading follow:
The parameter lists must be unique, either in the number of parameters or their data type.
The return value can be different (as long as the parameter lists are unique).
The list of declared exceptions can be different (as long as the parameter lists are unique).
For example, suppose a class has the following methods. Do these method declarations
follow the rules for valid method overloading?
public void send(String recipient, String message)
public boolean send(String recipient, StringBuffer message)
public void send(int id) throws UnknownHostException
public void send(float f)
public int send(String [] headers)
Because the parameter lists for these fi ve send methods are unique and unambiguous,
these methods do follow the rules for proper method overloading and could appear in the
same class. The key in overloading is that the parameter lists are unique enough that the
compiler can resolve the appropriate method.
The method signatures must be different for valid method overloading. The return
values and declared exceptions are irrelevant if the method signatures are unique. For
example, the following two method declarations are not valid method overloading because
they have the same signature:
public boolean send(String name, String address)
public void send(String recipient, String message)
Changing the return type is not suffi cient, and the names of the parameter does not help
the compiler resolve anything, so these two send methods could not appear in the same class.
Method Overloading and Data Type Promotion
There can be some confusion when the parameter types of overloaded methods are
related either by inheritance or promotion. For example, suppose we have the following
overloaded methods:
12. public String convert(int x) {
13. return “int”;
14. }
15. public String convert(short b) {
16. return “short”;
17. }
Search WWH ::




Custom Search