Java Reference
In-Depth Information
the type of the superclass. This is interesting because any method called on the object passed
in will be dispatched to the code for the subclass, not the superclass, which means that new
things can happen inside of old code.
As the name suggests, the real purpose of an interface is to give those who want to use an
object the set of operations that can be performed on the object. Just as the user interface of
a program determines how the human user can manipulate the program, the Java interface,
properly defined, tells a programmer how the object can be manipulated. The interface to an
object is, in fact, a user interface, but the users are programmers.
But the most important reason to use interfaces has to do with how they can clarify the overall
design of a system. When properly designed, an interface defines a semantic unit, that is, a set
of operations that give meaning to each other. As such, the interface should be thought of as
the basic unit of meaning in a Java program or a system of such programs. This connection
between the interface and meaning is generally not well understood, so we will look at an ex-
ample to see what I'm talking about.
Suppose we are building a system to keep track of statistics for baseball players. We could
try to keep all the information needed to generate all the possible kinds of statistics for every
player in a single class, but that would be missing some knowledge about the game (and the
statistics kept about the players). Instead, we will define different interfaces for the different
kinds of statistics and different kinds of players.
The most commonly known baseball statistics have to do with hitting. There are lots of dif-
ferent statistics that we could keep on a hitter, but we will define an interface that allows us to
keep track of only a few:
package examples;
* An interface that defines the notion of a batter
* in a baseball statistics package. Each at-bat will
* be recorded for the hitter, along with the result of
* that at-bat. Running totals of the important statistics
* will be available.
public interface Batter {
* The possible results of an at-bat for the hitter.
enum AtBatResult {
Search WWH ::

Custom Search