Java Reference
In-Depth Information
We also need to decide how to indicate that a Player object does not fill one of these roles.
One way would be to throw some exception on the methods just shown if the Player did not
fill the requested role. This would indicate that not fulfilling one of these roles is very unusual
and somehow wrong. But that's not the case with these roles; indeed, most Player objects will
not fill the catcher role. So we will take the approach of saying that if a Player object does
not fill a role, calling the get() method for that role on that Player object will return null .
This is similar to the convention in C of returning a marked value to indicate an error, which
we earlier railed against when we talked about exceptions. However, in this case it would be
very hard to ignore the error (which is one of the problems with the C approach), and in fact
the return of null does make sense semantically—after all, what this value tells us is that the
player in question doesn't have any of these sorts of statistics.
It would also be nice to find out before making a call to one of these methods whether the
Player was going to answer in the affirmative when asked if it filled a particular role. We
will do this in a way that is similar to how we tell what position a player fills, by defining
an enumeration for the possible roles and a pair of methods that will allow setting a role and
querying whether a role is held by the Player . Unlike the position, however, a Player can
have multiple roles, which will change how we implement this in a moment.
First, we will define the enumeration that sets out the statistical roles for a player. We will add
this enumeration to our Player interface:
* The roles that can be played by a player. These
* roles determine which statistics will be gathered
* about the player.
public enum Roles {
Batter, Fielder, Catcher
Next, we add two methods to our interface, one that lets us add a role and another that lets us
find out whether the Player has a role:
* Queries if the {@code Player} has the
* indicated role. Returns {@code true} if the
* player does have the role, and {@code false}
* otherwise. Note that a player can have multiple
Search WWH ::

Custom Search