Java Reference
In-Depth Information
Only a particular Animal object makes a specific sound, so the sound() method in this class does noth-
ing.
First of all, you enhance the class Dog by adding a method to display the sound that a dog makes:
public class Dog extends Animal {
// A barking method
@Override
public void sound() {
System.out.println("Woof
Woof");
}
// Rest of the class as before...
}
Directory "AnimalVoices"
You can also derive a class Cat from the class Animal :
public class Cat extends Animal {
public Cat(String aName) {
super("Cat");
// Call the base constructor
name = aName;
// Supplied name
breed = "Unknown";
// Default breed value
}
public Cat(String aName, String aBreed) {
super("Cat");
// Call the base constructor
name = aName;
// Supplied name
breed = aBreed;
// Supplied breed
}
// Return a String full of a cat's details
@Override public String toString() {
return super.toString() + "\nIt's " + name + " the " + breed;
}
// A miaowing method
@Override
public void sound() {
System.out.println("Miiaooww");
}
protected String name;
// Name of a cat
protected String breed;
// Cat breed
Search WWH ::




Custom Search