Java Reference
In-Depth Information
Q: What did we gain from this design?
A: We gained a benefit that might seem subtle but is an important
aspect of the Java language—one that demonstrates the robust-
ness and structure of the Java programming language. When it
comes time to inform the objects in the audience Vector of a
change in the score, we know that every object in that Vector is of
type FootballListener. This means we can invoke any method in
the FootballListener interface on every object in audience, and we
are guaranteed that each object has implemented the method.
Through this design, I have forced members of the audience Vec-
tor to have certain behaviors, and it was all accomplished using an
interface parameter of type FootballListener.
Q: Can you do this in other programming languages?
A: This type of benefit with interfaces is difficult to accomplish in lan-
guages that are not object oriented. We are using two key OOP
concepts: encapsulation and polymorphism. Interfaces in Java are
a powerful design tool, as long as you understand how they can
be used to improve the design of your applications. Read on!
Let's write a class that wants to listen to a football game. The following
ScoreBoard class implements the FootballListener interface.
public class ScoreBoard implements FootballListener
{
private String home, visitors;
private int homePoints, visitorPoints;
private int currentQuarter;
public ScoreBoard()
{
currentQuarter = 1;
}
public void updateScore()
{
System.out.println(“*************************************”);
System.out.println(home + “: “ + homePoints);
System.out.println(visitors + “: “ + visitorPoints);
displayQuarter();
System.out.println(“*************************************”);
}
public void displayQuarter()
{
if(currentQuarter > 0)
{
System.out.println(“Game is in quarter “
+ currentQuarter);
Search WWH ::




Custom Search