Java Reference
In-Depth Information
implementation, at which point there would be a problem. What we would
like is more than a campaign promise; we need some syntax that forces
Stretchable to remain implementation-free forever. If this was possible, then
the compiler could allow the inheritance from two classes that has a hierar-
chy in the style of Figure 4.15.
This syntax is precisely what an interface is.
the interface
4.4
The interface in Java is the ultimate abstract class. It consists of public abstract
methods and public static final fields, only.
A class is said to implement the interface if it provides definitions for all
of the abstract methods in the interface. A class that implements the interface
behaves as if it had extended an abstract class specified by the interface.
In principle, the main difference between an interface and an abstract
class is that although both provide a specification of what the subclasses
must do, the interface is not allowed to provide any implementation details
either in the form of data fields or implemented methods. The practical
effect of this is that multiple interfaces do not suffer the same potential
problems as multiple inheritance because we cannot have conflicting imple-
mentations. Thus, while a class may extend only one other class, it may
implement more than one interface.
The interface is an
abstract class that
contains no imple-
mentation details.
4.4.1 specifying an interface
Syntactically, virtually nothing is easier than specifying an interface. The inter-
face looks like a class declaration, except that it uses the keyword interface . It
consists of a listing of the methods that must be implemented. An example is
the Stretchable interface, shown in Figure 4.16.
The Stretchable interface specifies one method that every subclass
must implement: Stretch . Note that we do not have to specify that these
methods are public and abstract . Since these modifiers are required for
interface methods, they can and usually are omitted.
figure 4.16
The Stretchable
interface
1 /**
2 * Interface that defines stretch method to lengthen the longest
3 * dimension of a Shape
4 */
5 public interface Stretchable
6 {
7 void stretch( double factor );
8 }
 
 
Search WWH ::




Custom Search