Java Reference
In-Depth Information
full discussion of how the language chooses which available overloaded
method to invoke for a given invocation can be found in " Finding the
Right Method " on page 224 .
As you may have realized, constructors can also be overloaded in the
same way that methods are.
Overloading is typically used when a method or constructor can accept
the same information presented in a different form, as in the orbit-
sAround example, or when it can use a number of parameters, some of
which have default values and need not be supplied. For example, the
Body class might have two overloaded constructors: one that takes a
name and another Body object that it orbits around (as shown on page
55 ) and a second that takes only a name, indicating that body does not
orbit another body.
You should use overloading judiciously and carefully. While overloading
based on the number of arguments is usually quite clear, overloading
based on the same number but different types of arguments can be con-
fusing. When you add varargs methods to the mix, even overloading
based on different numbers of parameters can become confusing when
reading or writing invocations of those methodsdoes that two-argument
invocation match two fixed parameters, or one fixed parameter and a
sequence with one element, or just a sequence with two elements? For
example, the following shows extremely poor use of overloading:
public static void print(String title) {
// ...
}
public static void print(String title, String... messages) {
// ...
}
public static void print(String... messages) {
// ...
}
Given the invocation
 
Search WWH ::




Custom Search