Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 6 ■ OBJECT-ORIENTED PROGRAMMING

Listing 6-8. The finished Cat class


package com.apress.java7forabsolutebeginners.examples.animalKingdom;


class Cat extends Mammal implements Predator, Carnivore {


private static int numberOfCats;


Cat() {
numberOfCats++;
}


public static final int getNumberOfCats() {
return numberOfCats;
}


@Override
protected void sayWhatIAm() {
System.out.println("I am a cat");
super.sayWhatIAm();
}


// implement the super class's abstract methods
@Override
void speak() {
System.out.println("The cat says, \"meow.\"");
}


// here's our example of overloading
void chase(Mouse mouse) {
// chase a mouse
}
public void chase (Object tail) {
// chase one's tail
}


// 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
}
}


Because we use the Cat class throughout the earlier examples, you already know it extends the
Mammal class. As we discussed in the “Modeling Behavior through Interfaces” section, it also implements
the Predator and Carnivore interfaces. After all, cats are predators and carnivores (see Listing 6-9).

Free download pdf