Java Reference
In-Depth Information
//Notify the audience which quarter just ended.
int size = audience.size();
for(int i = 0; i < size; i++)
{
FootballListener current =
(FootballListener) audience.elementAt(i);
current.endOfQuarter(quarter);
}
}
}
Classroom Q & A
Q: How do listeners get into the audience Vector of the FootballGame
class?
A: Look at the addFootballListener() method and you will see a call
to add() invoked on the Vector. This adds the parameter f to the
audience Vector.
Q: Sure, but how exactly does the FootballGame class force its audi-
ence to implement the FootballListener interface?
A: Two specific design techniques are used. The audience Vector is a
private field, so no one outside the class can access the audience
Vector directly. The only changes to audience occur in the
addFootballListener() method. Also, the parameter is a Football-
Listener, so the only way to invoke addFootballListener() is to pass
in a FootballListener object.
Q: But FootballListener is an interface. I thought you couldn't instan-
tiate a FootballListener object.
A: True, you can't. But you can write a class that implements Football-
Listener, and instances of this class will be of type FootballListener.
Q: Why?
A: Because of polymorphism. If a class named CellPhone imple-
ments FootballListener, a CellPhone object is a FootballListener
object. The design of our FootballGame class is such that the only
way to be a member of the audience Vector is to write a class that
implements FootballListener.
Search WWH ::




Custom Search