Java Reference
In-Depth Information
public static void main(String[] args)
{
// Create two objects of class Dog
Dog dog1 = new Dog("Fido",2, 12.95,"Spaniel");
Dog dog2 = new Dog("Atila",3, 20.75,"Hound");
// Create a Cat and a Bird object
Cat cat1 = new Cat("Fifo", 3, 15.95, "Siamese");
Bird bird1 = new Bird("Tweety", 1, 2.55, "Yellow");
// Display pet data using superclass and subclass
// methods
dog1.getName();
// Method in superclass
dog2.getName();
// Methods in superclass
dog2.getLocation();
dog2.getSpecData(); // Method in subclass
bird1.getName();
bird1.getSpecData();
}
}
Do not assume that an abstract class should only have abstract meth-
ods. The general rule is to have as much functionality as possible in the
superclass, whether or not it is an abstract class. Instance fields and
non-abstract methods should all be in the superclass. Operations that
cannot be implemented in the superclass are the only ones that should be
in the subclasses. This approach is the one used in the PetStore program
listed previously.
One of the advantages of using inheritance is greater code reusability.
Suppose that the pet store owner decided to expand the store line to in-
clude pet lizards. In this case the functionality for keeping track of the
name, location, and price of each pet lizard is already in place. The
PetStore program could be easily modified by implementing a new class
called Lizard, that extends Pet. Only the data and operations that are spe-
cific for each pet lizard would have to be implemented in the new class.
Search WWH ::




Custom Search