Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 6 ■ OBJECT-ORIENTED PROGRAMMING


Listing 6-9. The finished Dog class

package com.apress.java7forabsolutebeginners .examples.animalKingdom;

class Dog extends Mammal implements Predator, Carnivore, Scavenger {
// implement the super class's abstract methods
@Override
void speak() {
System.out.println("The dog says, \"bark.\"");
}
// methods for the Predator interface
@Override public void hunt() {
// go hunting
}

// methods for the Carnivore interface
@Override public void eat (Object freshMeat) {
// eat fresh meat
}

// methods for the Scavenger interface
@Override public void eat (Object carrion, boolean tooOld) {
if (tooOld) {
// don't eat that!
} else {
// munch away
}
}
}

The Dog class also extends Mammal and implements the Predator and Carnivore classes. However,
dogs also scavenge for food, so the Dog class also implements the Scavenger Interface.
Now, let's move onto an animal that is still a mammal but that has different behaviors: a mouse.
Listing 6-10 defines our Mouse object.

Listing 6-10. The finished Mouse class

package com.apress.java7forabsolutebeginners .examples.animalKingdom;

class Mouse extends Mammal implements Herbivore{
// implement the super class's abstract methods
@Override
void speak() {
System.out.println("The mouse says, \"squeak.\"");
}
// methods for the Herbivore interface
@Override public void eat (Object plantMatter) {
// eat plants
}
}
Free download pdf