Abstract Methods in Interfaces
An interface defines a contract by specifying a set of abstract and default method declarations, but provides implementations only for the default methods—not for the abstract methods. The abstract methods in an interface are all implicitly abstract and public by virtue of their definitions. Only the modifiers abstract and public are allowed, but these are invariably omitted. An abstract method declaration has the following simple form in a top-level interface:
return_type method_name
(
formal_parameter_list
)
throws_clause
;
An abstract method declaration is essentially a method header terminated by a semicolon (;). Note that an abstract method is an instance method whose implementation will be provided by a class that implements the interface in which the abstract method is declared. The throws clause is discussed in §7.5, p. 388.
The interface Playable shown below declares an abstract method play(). This method is implicitly declared to be public and abstract. The interface Playable defines a contract: To be Playable, an object must implement the method play().
interface Playable {
void play(); // Abstract method: no implementation
}
An interface that has no direct superinterfaces implicitly includes a public abstract method declaration for each public instance method from the java.lang.Object class (e.g., equals(), toString(), hashCode()). These methods are not inherited from the java.lang.Object class, as only abstract method declarations are included in the interface. Their inclusion allows these methods to be called using an interface reference, and their implementation is always guaranteed at runtime as they are either inherited or overridden by all classes.
In contrast to the syntax of abstract methods in top-level interfaces, abstract methods in top-level classes must be explicitly specified with the keyword abstract, and can have public, protected, or package accessibility.
Functional interfaces, meaning interfaces with a single abstract method, are discussed together with lambda expressions in §13.1, p. 675.
The rest of this chapter provides numerous examples of declaring, implementing, and using interfaces.