Overloading a Method
Purpose:
- To provide different definitions for the same capability with different parameters.
Mechanics
<modifiers> <return type1> <method name>(<parameter list1>) {/* Java statements */
}- <modifiers> <return typeN> <method
name>(<parameter listN>) {
- /* Java statements */
}
Example:
public void myMethod(int a, int b) {/* Java statements */
}- public void myMethod(int a) {
- /* Java statements */
}
Usage:
- When Java encounters a method call, it determines which
specific method to execute based on the following:
- the class of the instance the call is made on
- the name of the method call
- and the number and type of parameters passed to the method
- Note in particular that Java does not look at the <return type> of the method. Thus while different definitions of the same behavior with different parameters can have different return types, different definitions of the same behavior with the same parameters are not allowed.
email suggestions to: cs015tas@cs.brown.edu
