THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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


print("Hello"); // which print?


which print method is to be invoked? While not obvious, this example actually has clearly defined
behavior: a fixed-argument method will always be selected over a varargs methodagain, see "Finding the
Right Method" on page 224 for details. So in this case it will invoke the print method that takes a single
String parameter. In contrast, this invocation is ambiguous and results in a compile-time error:


print("Hello", "World"); // INVALID: ambiguous invocation


This could be a string and a one-element sequence, or a two-element sequence. The only way to resolve this
ambiguity is to pass actual arrays if you intend to match with the sequence parameters:


print("Hello", new String[] {"World"});
print( new String[] { "Hello", "World" });


The first invocation now clearly matches the two-parameter print method, and the second clearly matches
the single-sequence-parameter print method.


You can best avoid such situations by never overloading methods in a way that leads to such ambiguity.


Exercise 2.17: Add two turn methods to Vehicle: one that takes a number of degrees to turn and one that
takes either of the constants Vehicle.TURN_LEFT or Vehicle.TURN_RIGHT.


2.9. Importing Static Member Names


Static members should generally be referenced using the name of the class to which the static member
belongs, as in System.out or Math.sqrt. This is usually the best practice because it makes clear what
your code is referring to. But using the name of the class every time you reference a static field or method can
sometimes make your code cluttered and more difficult to understand. For example, suppose you needed to
define the mathematical function to calculate the hyperbolic tangent (tanh).[3] This can be calculated using the
Math.exp function:

Free download pdf