Java Reference
In-Depth Information
methods? You don't know what class will be using them! The answer lies in the fact that
you use an interface name anywhere a class name can be used, as you learned earlier. By
defining your method arguments to be interface types, you can create generic arguments
that apply to any class that might use this interface.
Consider the interface Trackable , which defines methods (with no arguments) for
track() and quitTracking() . You might also have a method for beginTracking() ,
which has one argument: the trackable object itself.
What class should that argument be? It should be any object that implements the
Trackable interface rather than a particular class and its subclasses. The solution is to
declare the argument as simply Trackable in the interface:
public interface Trackable {
public abstract Trackable beginTracking(Trackable self);
}
Then, in an actual implementation for this method in a class, you can take the generic
Trackable argument and cast it to the appropriate object:
public class Monitor implements Trackable {
public Trackable beginTracking(Trackable self) {
Monitor mon = (Trackable) self;
// ...
}
}
Extending Interfaces
As you can do with classes, you can organize interfaces into a hierarchy. When one inter-
face inherits from another interface, that “subinterface” acquires all the method defini-
tions and constants that its “superinterface” declared.
To extend an interface, you use the extends keyword just as you do in a class definition:
interface PreciselyTrackable extends Trackable {
// ...
}
Note that unlike classes, the interface hierarchy has no equivalent of the Object class—
there is no root superinterface from which all interfaces descend. Interfaces can either
exist entirely on their own or inherit from another interface.
Note also that unlike the class hierarchy, the inheritance hierarchy can have multiple
inheritance. For example, a single interface can extend as many classes as it needs to
Search WWH ::




Custom Search