Java Reference
In-Depth Information
You may be wondering what type the parameter sequence bodies has
inside setOrbiters quite simply it is an array of Body objects. Declaring a
parameter as a sequence is nothing more than asking the compiler to
construct an array for you and to set its elements to be the arguments
actually passed for the sequence. When you invoke a method, the com-
piler will match each supplied argument to a named parameter. If the
compiler finds a sequence parameter then it will bundle all the remaining
arguments into an array of the type specified by the sequence paramet-
erremember a sequence parameter must be the last declared paramet-
er. Of course, those arguments must be of the right type to be stored
in the array. If no arguments are left to store in the array then a zero-
length array is created and passed as the argument. Knowing this, you
could save the compiler the trouble and pass an array yourself:
Body[] marsMoons = { phobos, deimos };
mars.setOrbiters(marsMoons);
But in most cases it is easier to just let the compiler do its job.
Sometimes the compiler will need some help working out what you in-
tended a particular method invocation to mean. For example, suppose
you invoke setOrbiters with the single argument null . Does that mean
to pass null as the array (and so have no array) or does it mean to have
an array of length one with a null entry? The compiler can't be sure so
it will give you a warning. To remove the ambiguity you need to cast
null to a suitable typefor a sequence parameter of type T , if you cast to
T then you get an array of T of length one with a null enTRy; if you cast
to T[] then you get a null array reference. Other ambiguities can arise
in the context of method overloading, but we'll get to those later (see
" Overloading Methods " on page 69 ).
You've already seen an example of another varargs method in use, but
may not have realized it. The printf method that was introduced on
page 23 is declared to take a String and a sequence of Object s. For each
format specifier in the format string, the method expects a correspond-
ing object argument to be passed in.
 
Search WWH ::




Custom Search