Java 7 for Absolute Beginners

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

As with our other animal objects, the Mouse class extends Mammal. However, a mouse is not a
carnivore, a predator, or a scavenger. Instead, a mouse is an herbivore, so we make our Mouse class
implement the Herbivore interface.
Now let's move onto the interfaces. We start with the Predator interface (see Listing 6-11).


Listing 6-11. The Predator interface


package com.apress.java7forabsolutebeginners .examples.animalKingdom;


interface Predator {
public void hunt();
}


All predators hunt, so our Predator interface includes a hunt() method. Any class that implements
this Predator interface must implement a hunt() method with the same signature (void and with no
arguments). If we have a Drone class that implements a Predator interface, that interface might
implement a launch(Missile hellfire) method, which is different from a Predator interface that suits
animals (at least outside the realm of science fiction).
Let's move on to the Carnivore interface, shown in Listing 6-12.


Listing 6-12. The Carnivore interface


package com.apress.java7forabsolutebeginners .examples.animalKingdom;


interface Carnivore {
public void eat(Object freshMeat);
}


Carnivores eat fresh meat, so we specify an object named freshMeat as the argument to the
interface's only method.
Compare that to the Scavenger interface, shown in Listing 6-13.


Listing 6-13. The Scavenger interface


package com.apress.java7forabsolutebeginners .examples.animalKingdom;


interface Scavenger {
public void eat(Object carrion, boolean tooOld);
}


Scavengers eat whatever meat they can find. Of course, one issue is that some meat might be too
foul to eat, so we include a boolean argument that we can test for that problem.
Finally, we come to our Herbivore interface, as shown in Listing 6-14.


Listing 6-14. The Hervibore interface


package com.apress.java7forabsolutebeginners .examples.animalKingdom;


interface Herbivore {
public void eat(Object plantMatter);
}

Free download pdf