Java Reference
In-Depth Information
Directory "DuplicateObjects"
You can now derive a class
PetDog
from
Dog
that contains a
Flea
object as a member:
public class PetDog extends Dog {
// Constructor
public PetDog(String name, String breed, String fleaName, String
fleaSpecies) {
super(name, breed);
petFlea = new Flea("Max","circus flea");
// Initialize petFlea
}
// Copy constructor
public PetDog(PetDog pet) {
super(pet);
// Call base copy
constructor
petFlea = new Flea(pet.petFlea);
// Duplicate the flea
}
// Return the flea
public Flea getFlea() {
return petFlea;
}
@Override
public void sound() {
System.out.println("Woof");
}
// Return a String for the pet dog
@Override
public String toString() {
return super.toString() + " - a pet dog.\nIt has a flea:\n" +
petFlea;
}
protected Flea petFlea;
// The pet flea
}
Directory "DuplicateObjects"
This class defines a specialized type of
Dog
object that has a flea. To make it possible to clone a
PetDog
object, you implemented a copy constructor. Note how the copy constructor passes the
PetDog
object to
the
Dog
class copy constructor. This is legal because the
Dog
class copy constructor has a parameter of
type
Dog
and a
PetDog
object is a specialized type of
Dog
. In general you can pass an object of any type
that is a subclass of the parameter type to a method.
You can try out creating and duplicating a
PetDog
object with the following code: