Java Reference
In-Depth Information
Note You can always tell if you're right to make a new class by asking a simple question: Is this new class a
member of the old class? That's called the “is-a” test or the “is-one-of” test. A cat is a mammal, so we can make
our Cat class extend our Mammal class. The same is true for our Dog and Mouse classes. If we had a Snake class, it
would not be wise to create it by extending the Mammal class. It's not always so obvious, but it's a good place to
start when you need to figure out which class your new class should extend.
Of course, there are substantial differences among cats, dogs, and mice, and we cover how to model
those differences when we get to Polymorphism, later in this chapter.
Multiple Inheritance
Java does not support multiple inheritance (though interfaces give us a way to get most of the benefits of
multiple inheritance without the one big problem, which we discuss shortly, that comes with it). That is,
an object cannot extend more than one parent object. Other languages (such as C++) do permit
inheriting from more than one parent. The designers of Java determined that Java could be made
without that level of complexity. The problem with multiple inheritance is that a single class can extend
two other classes, and those two classes might in turn extend the same ancestor class. How would your
code know which ancestor class provides the right information? That's sometimes called “the diamond
problem,” because it looks like a diamond when graphed (see Figure 6-1).
Figure 6-1. The diamond problem
You might think that the diamond problem is easy to avoid. However, remember that most software
is created by multiple teams of people. At the time of this writing, I'm working with two development
teams and a testing team in another country to create a software product that no fewer than 75 other
software development teams in the same company will use as the basis for yet more software. In those
circumstances, it's not hard to imagine how one team might implement a class that extends a class, the
other team might extend the same class, and, if we had multiple inheritance, someone in the client
teams might try to extend both and run right into the diamond problem. It's easy to get into a situation
where a single method might extend methods from two other classes. How would the compiler know
which method we meant to use? Java prevents all that by not providing multiple inheritance.
Search WWH ::




Custom Search