Java Reference
In-Depth Information
Forcing Behavior on a Class
An interface can be used as a parameter to a method, as we saw earlier in this
chapter in both the Payroll class and the HumanResources class. For example,
the payEmployee() method in Payroll has a Payable parameter. In that exam-
ple, the purpose of using the Payable interface was to expose certain methods
of the Employee class to the Payroll object, while hiding the other methods in
Employee.
You can also use interface parameters to force classes to implement a partic-
ular interface. By forcing a class to implement a particular interface, you are
forcing the class to contain certain methods.
This type of design is used throughout Java programming, and we will see
several important examples of interface parameters in the remainder of
this topic, including GUI event handling, threads, and JavaBeans.
For example, imagine that we have written a program that updates an audi-
ence of a football game every time the score changes. The audience in this
example could be someone waiting for updates on a cell phone or PDA, or
someone at home watching the scores change on a Web site, or a restaurant
that flashes the scores on an electronic scoreboard for its customers. In these
examples, each audience is an example of a listener. They are waiting and lis-
tening for a particular event to occur. We need to keep track of all these differ-
ent types of listeners. This heterogeneous collection of listeners will not be too
difficult to create because we saw in Chapter 9, “Collections,” that the collec-
tions framework classes hold objects of type Object, which is any object.
However, we need a mechanism for notifying listeners when the score of the
football game changes. How do we do this? Well, we are going to invoke a
method on each listener. Which method will we invoke? And more impor-
tantly, how do we know that the listener has implemented the method we
want to invoke?
By using an interface parameter, we will force anyone who wants an update
of the football score to implement an interface named FootballListener. The
FootballListener interface is defined as follows:
public interface FootballListener
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
Search WWH ::




Custom Search