Java Reference
In-Depth Information
Interfaces
An interface is a type that specifies method headings (and, as we will see, possibly defined
constants as well). The syntax for defining an interface is similar to the syntax of defining a
class, except that the word interface is used in place of class and the method headings
without any method body (but followed by a semicolon) are given only.
Note that an interface has no instance variables and no method definitions.
A class can implement any number of interfaces. To implement an interface, the class
must include
implements Interface_Name
at the end of the class heading and must supply definitions for the method headings given
in the interface. If the class does not supply definitions for all the method headings given
in the interface, then the class must be an abstract class and the method headings without
definitions must be abstract methods.
EXAMPLE
See Displays 13.1, 13.2, and 13.3.
Self-Test Exercises
1. Can you have a variable of an interface type? Can you have a parameter of an
interface type?
2. Can an abstract class ever implement an interface?
3. Can a derived class have two base classes? Can it implement two interfaces?
4. Can an interface implement another interface?
PITFALL: Interface Semantics Are Not Enforced
As far as the Java compiler is concerned, an interface has syntax but no semantics. For
example, the definition of the Ordered interface ( Display 13.1 ) says the following in
a comment:
/**
For objects of the class o1 and o2,
o1.follows(o2) == o2.preceded(o1).
*/
You might have assumed that this is true even if there were no comment in the
interface. After all, in the real world, if I precede you, then you follow me. However,
that is giving your intuitive interpretation to the word “ precedes ”.
(continued)
 
Search WWH ::




Custom Search