Java Reference
In-Depth Information
2.8. Overloading Methods
Each method has a signature, which is its name and the number and
types of its parameters. Two methods can have the same name if they
have different numbers or types of parameters and thus different sig-
natures. This feature is called overloading because the simple name of
the method has an overloaded (more than one) meaning. When you in-
voke a method, the compiler uses the number and types of arguments
to find the best match from the available overloads. Here are some or-
bitsAround methods for our Body class that return TRue if the current body
orbits around the specified body or a body with the specified identifier:
public boolean orbitsAround(Body other) {
return (orbits == other);
}
public boolean orbitsAround(long id) {
return (orbits != null && orbits.idNum == id);
}
Both methods declare one parameter, but the type of the parameter dif-
fers. If the method orbitsAround is invoked with a Body reference as an
argument, the version of the method that declares a Body parameter is
invokedthat version compares the passed in reference to the body's own
orbits reference. If orbitsAround is invoked with a long argument, the ver-
sion of the method that declares a long parameter is invokedthat ver-
sion of the method compares the passed in identification number with
the idNum field of the object it orbits. If the invocation matches neither of
these signatures, the code will not compile.
For varargs methods, a sequence parameter T... is treated as being a
parameter of type T[] for overloading purposes. So if two signatures dif-
fer only because one declares a sequence and the other an array, then a
compile-time error occurs.
The signature does not include the return type or the list of thrown ex-
ceptions, and you cannot overload methods based on these factors. A
 
Search WWH ::




Custom Search