Java Reference
In-Depth Information
the existing methods to enhance or replace the functionality. Inheritance features
of an object-oriented language such as Java yields many benefits, including:
Code reuse —An abstract base class can be built that contains a lot of common
logic, but by itself is incomplete. The subclasses that extend the base class
can complete the functionality while reusing the common features of the
base class. The result is that you can have a number of implementations of a
feature without rewriting or duplicating the common aspects.
Enhancement and specialization —Sometimes you might decide to extend a
class to add more useful features. This is a common reason to extend collec-
tion classes. For example, one might decide to extend the ArrayList class to
only support Strings called StringArray. New features could then be added,
such as features for searching based on a regular expression.
Common interface —Although using an actual interface instead of an abstract
class might be a better choice here, it is possible to use a base class as a com-
mon interface in a framework or some other sort of pluggable system.
There are other benefits of inheritance, but there are also many risks. Inheritance
is notoriously inflexible for modeling business domains. Business is often too
complex to commit to a single hierarchy. This is especially true in a language such
as Java, where you can only extend from a single superclass (single inheritance).
Even if your programming language of choice supports multiple inheritance, it
still may not be the best choice.
Many patterns and best practices that have emerged over the years have sug-
gested favoring alternatives to inheritance. These alternatives include:
Favor composition over inheritance —A good example of this is roles that people
play. A generally poor design would have a Manager class extending from
Employee, which extends from Person. That is to say that a Manager “is an”
Employee and an Employee “is a” Person. This may indeed be true, but
what happens when that same person is a Customer? For example, a Man-
ager decides to shop at his own store. Where does a person who is both a
Customer and an Employee fit in that hierarchy? Certainly a Customer is
not necessarily an Employee, nor is an Employee necessarily a customer.
Instead of modeling this using inheritance, you might want to consider
using composition. Change the “is a” relationship to a “has a” relationship
by keeping a collection of Roles on the Person class. That way a person can
have any combination of the roles described.
Favor interfaces over abstract classes —In cases in which your intent is to have a
common interface to describe a certain set of functionality, you're better off
Search WWH ::




Custom Search