Java Reference
In-Depth Information
This is a Flea
It's Max the circus flea
How It Works
The first block of output shows the details of the original pet. The next block shows that the duplicate
pet has exactly the same characteristics as the original. The third block shows the details of the duplicate
after the dog's name and its flea's name have been changed. The last block of output shows that the ori-
ginal pet is unaffected by the change to the duplicate, thus demonstrating that the objects are completely
independent of one another.
It is important to ensure that all mutable data members are duplicated in a copy constructor operation.
If you simply copy the references for such data members, changes to one object affect the copy because
they share the same objects as members. The copy constructor in the PetDog class creates a new Flea
object for the new PetDog object by calling the copy constructor for the Flea class. The members inher-
ited from Dog are both String objects. These are immutable, so you don't need to worry about creating
duplicates of them.
METHODS ACCEPTING A VARIABLE NUMBER
OF ARGUMENTS
You can write a method so that it accepts an arbitrary number of arguments when it is called, and the argu-
ments that are passed do not need to be of the same type. Such methods are called Varargs methods. The
reason I have waited until now to mention this is that understanding how this works depends on having an
understanding of the role of the Object class. You indicate that a method accepts a variable number of ar-
guments by specifying the last parameter as follows:
Object ... args
The method can have zero or more parameters preceding this, but this must be last for obvious reasons.
The ellipsis (three periods) between the type name Object and the parameter name args enables the com-
piler to determine that the argument list is variable. The parameter name args represents an array of type
Object[] , and the argument values are available in the elements of the array as type Object . Within the
body of the method, the length of the args array tells you how many arguments were supplied.
Let's consider a very simple example to demonstrate the mechanism. Suppose you want to implement
a static method that accepts any number of arguments and outputs the arguments to the command line —
whatever they are. You could code it like this:
public static void printAll(Object ... args) {
for(Object arg : args) {
System.out.print(" " + arg);
}
System.out.println();
}
Search WWH ::




Custom Search