Java Reference
In-Depth Information
12.6
E SSENTIAL AND N ONESSENTIAL
So far, we have walked you through a very simple example, and we have made
sound choices at every step. In more complex cases, even the best of us will
make mistakes. We will head down blind alleys. We will group things together
that might belong in separate abstract categories, but should, perhaps, share an
interface. These are not so much errors as judgment calls, and skill at recogniz-
ing them and making the correct decisions comes only with experience.
For now, the most important questions to ask include:
Do I need this class?
We are often tempted to create too many inherited classes. When we
seek more generic, higher level abstractions, it is often possible to use only
the more abstract class. Of course, it is possible to carry that tendency too
far. If your methods contain a lot of “if's” to handle various subtypes, that
might be a case where you should inherit and overload the method.
Should I get functionality by inheritance or composition?
Inheritance should be reserved only for cases where a class is a more
specific variety of the base class. For example, you might have a Person
class, and then you might have Employee and Customer classes inherit
common attributes and methods from Person. This is frequently called an
“is-a” relationship, as in “A User is a Person.” If your proposed inheritance
relationship makes sense phrased that way, it might well be a good
candidate for inheritance.
Composition is when you use a class as an attribute. To extend our
example, you might have an Address class. You might be tempted to have
Person inherit from Address. But a Person is not an Address. Try it: “A
Person is an Address.” Nope. Instead, you should just have an instance of
the Address class as an attribute of Person. Such a relationship is often
called a “has-a” relationship, as in “A Person has an Address.” If the
relationship makes sense phrased that way, it is a good candidate for
composition. Another way to recognize that you've wrongly used inheri-
tance is if you end up having a radically different class inherit from the
same base class. For example, suppose you have a class, Building. Would
it make sense for Building and Person to inherit from Address? Are
Buildings and Persons more specific instances of the same general type of
thing? No, they are not. Building and Person should get Address
functionality by composition.
Search WWH ::




Custom Search