Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 6 ■ OBJECT-ORIENTED PROGRAMMING


The Herbivore interface is parallel to the Carnivore and Scavenger interfaces, but herbivores eat
plants, so we specify an object named plantMatter as the only argument.
Finally, here's a program class, called AnimalVoices, that lets our animals speak (see Listing 6-15).

Listing 6-15. Getting our animals to speak

package com.apress.java7forabsolutebeginners .examples.animalKingdom;

public class AnimalVoices {

public static void main(String[] args) {
// create instances of our animals
Cat cat = new Cat();
Dog dog = new Dog();
Mouse mouse = new Mouse();

// let our animals speak
cat.speak();
dog.speak();
mouse.speak();
}

}

As you can see, all it does is create an instance of each kind of animal and then have each one speak.

A Lesson about Granularity


Five classes and four interfaces might seem like a lot of objects to get three animals to make their
appropriate sounds. Honestly, if I were writing a program to produce three lines of text, I'd write just one
class. However, the purpose of the animal kingdom example was to show how to model a (not very)
complex system in Java.
If I were really writing a system to model the animal kingdom, I'd have many more classes. For
starters, if I were doing this for real, I wouldn't pass generic objects to the eat methods. I'd have an
abstract class called Food and concrete classes called FreshMeat, Carrion, and PlantMatter and very likely
subclasses from those, too.
If you “chunk up” your program into as many classes and interfaces as possible, you gain two
things:


  • Extensibility

  • Maintainability


Extensibility means that you can easily make your program do more than it does now. In the case of
our animal program, we could quickly add more animals and make those animals do more things (such
as walk, swim, play, and sleep). If we expand the program, we might also expand the food details such
that the PlantMatter class has Nut and Grain subclasses.
Maintainability means that you can easily find the spot where your code is wrong when you find an
error. If all your code is in just a few classes (or worst of all, one class), you have a harder time figuring
out the problem. Sure, the debugger gets you to the right line, but you won't know whether the problem
is in your definition of an animal or your definition of a mammal or your definition of its behavior (such
Free download pdf