Java Reference
In-Depth Information
return species;
}
public void sound() {
System.out.println("Psst");
}
// Present a flea's details as a String
public String toString() {
return super.toString() + "\nIt's " + name + " the " + species;
}
// Override inherited clone() to make it public
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
private String name; // Name of flea!
private String species; // Flea species
}
We have defined accessor methods for the name and the species. We don't need them now but they will
be useful later. By implementing the
Cloneable
interface we are indicating that we are happy to clone
objects of this class. Since we have said that
Flea
is cloneable, we must implement the
Cloneable
interface in the base class, so the class
Animal
needs to be changed to:
public class Animal implements Cloneable {
// Details of the class as before...
}
No other changes are necessary to the
Animal
class here. We can now define a class
PetDog
that
contains a
Flea
object as a member that is also cloneable:
public class PetDog extends Animal implements Cloneable {
// Constructor
public PetDog(String name, String breed) {
super("Dog");
petFlea = new Flea("Max","circus flea"); // Initialize petFlea
this.name = name;
this.breed = breed;
}
// Rename the dog
public void setName(String name) {
this.name = name;
}
// Return the dog's name
public String getName() {
return name;
}