Java Reference
In-Depth Information
Extending Multiple Interfaces
In Java, a class can only extend one parent class. (Multiple inheritance is not
allowed.) Interfaces are not classes, however, and an interface can extend more
than one parent interface. The extends keyword is used once, and the parent
interfaces are declared in a comma-separated list.
For example, if the HockeyListener interface extended both SportsListener
and EventListener, it would be declared as:
public interface HockeyListener extends SportsListener, EventListener
Any class that implements this HockeyListener interface must implement
all the methods in HockeyListener, SportsListener, and EventListener.
You might be curious to know what happens if an interface has two
parents and each parent declares the exact same method. For example, if
SportsListener and EventListener both contain a playBall() method, how
does this affect a class that implements HockeyListener? Well, because it
does not make sense for a class to have two playBall() methods, only one
is required of the class.
Tagging Interfaces
The most common use of extending interfaces occurs when the parent interface does not
contain any methods. For example, the MouseListener interface in the java.awt.event pack-
age extended java.util.EventListener, which is defined as:
package java.util;
public interface EventListener
{}
An interface with no methods in it is referred to as a tagging interface . Why define
an interface with no methods in it? Well, there are two basic design purposes of tagging
interfaces:
Creates a common parent. As with the EventListener interface, which is extended
by dozens of other interfaces in the Java API, you can use a tagging interface to
create a common parent among a group of interfaces. For example, when an inter-
face extends EventListener, the JVM knows that this particular interface is going to
be used in an event delegation scenario.
Adds a data type to a class. This situation is where the term tagging comes from.
A class that implements a tagging interface does not need to define any methods
(since the interface does not have any), but the class becomes an interface type
through polymorphism.
continued
Search WWH ::




Custom Search