Java Reference
In-Depth Information
}
Directory "AnimalVoices"
Just to make it a crowd, you can derive another class — of ducks:
public class Duck extends Animal {
public Duck(String aName) {
super("Duck");
// Call the base constructor
name = aName;
// Supplied name
breed = "Unknown";
// Default breed value
}
public Duck(String aName, String aBreed) {
super("Duck");
// Call the base constructor
name = aName;
// Supplied name
breed = aBreed;
// Supplied breed
}
// Return a String full of a duck's details
@Override
public String toString() {
return super.toString() + "\nIt's " + name + " the " + breed;
}
// A quacking method
@Override
public void sound() {
System.out.println("Quack quackquack");
}
protected String name;
// Duck name
protected String breed;
// Duck breed
}
Directory "AnimalVoices"
The data members of both classes are protected, so they are accessible in any derived class, but not from
any class that is not in the same package.
You can fill the whole farmyard, if you need the practice, but three kinds of animal are sufficient to show
you how polymorphism works.
You need a program that uses these classes. To give the classes a workout, you can create an array of type
Animal and populate its elements with different subclass objects. You can then select an object randomly
from the array, so that there is no possibility that the type of the object selected is known ahead of time.
Here's the code to do that:
Search WWH ::




Custom Search