Java Reference
In-Depth Information
The first of these, associating the various interfaces and classes we have defined for gathering
and reporting the different kinds of statistics with a Player object, is often done through the
type system by constructing a hierarchy. And we can almost do this, saying that every Player
is also a Batter , and every Batter is a Fielder . If we took this approach, then we would
change our Batter interface to begin with:
public interface Batter extends Fielder {
and our Player interface to begin with:
public interface Player extends Batter {
and change the implementations as well. Thus every Player would also be a Batter and a
Fielder , and would support all of the methods needed for the statistics reporting.
But this doesn't really work. To begin with, we still have the Catcher interface to insert into
the hierarchy, and will someday have to extend the set of classes to include a Pitcher in-
terface. In the real world we are trying to represent, all catchers are also fielders and batters,
but there are special statistics that apply only to catchers. If we make Catcher a superclass of
Player , we get the “is a” relationship right, but then we have trouble getting from a Player
object to a Catcher interface. Worse still, not all batters are fielders (because of designated
hitters). Similarly, if we add pitchers, we will have players who are not batters (at least in the
American League), but are fielders.
It is inconvenient when the world doesn't fit our notion of a type system, but it happens. When
it does, one thing we could do is simply ignore the world. We could, for example, say that
designated hitters are fielders who just never field, or that pitchers in the American League
are batters who never get enough plate appearances. Or we could complicate our type hier-
archy, introducing special interfaces for American League pitchers and designated hitters, and
wedge in catchers someplace or other.
Or we could do the right thing and decide that we can't capture the relationship between the
various statistical classes with the type hierarchy. A simpler solution is to say that a player
may have a number of roles, and each of those roles can be represented by a different interface
to a different underlying object. So a Player can be a Batter , a Fielder , and a Catcher , or
any subset of the three (and, when we add an interface for Pitcher , a Player could be one of
those as well).
Search WWH ::

Custom Search