Java Reference
In-Depth Information
values of various types, where the formatting is specified by the first argument. System.out happens to
be of type PrintStream so you can use printf() to produce formatted output to the command line. I
discuss how you use the printf() method to produce output with more precise control over the format
in which it is displayed in Chapter 8 in the context of streams.
Limiting the Types in a Variable Argument List
You don't have to specify the type of the variable argument list as type Object ; you can specify it as any
class or interface type. The arguments must be of the type that you specify, or any subtype of that type. Spe-
cifying the type of the variable argument list as Object maximizes flexibility because any types of argument
can be supplied, but there may be occasions where you want to restrict the types of the arguments that can
be supplied. For example, if you want to define a method that computes the average of an arbitrary number
of values that are to be supplied as individual arguments then you really want to be sure that the arguments
can only be numerical values. Here's how you could do this:
public static double average(Double ... args) {
if(args.length == 0) {
return 0.0;
}
double ave = 0.0;
for(double value : args) {
ave += value;
}
return ave/args.length;
}
In this case the arguments must be of type Double or of a type derived from Double , or — because of
autoboxing conversion supplied by the compiler — of type double .
CASTING OBJECTS
You can cast an object to another class type, but only if the current object type and the new class type are
in the same hierarchy of derived classes, and one is a superclass of the other. For example, earlier in this
chapter you defined the classes Animal , Dog , Spaniel , PetDog , Cat , and Duck , and these are related in the
hierarchy shown in Figure 6-5 .
FIGURE 6-5
 
 
Search WWH ::




Custom Search