Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


Creating an Interface

To create an interface, you must write both the interface declaration and the interface body.
interfaceDeclaration {
    interfaceBody
}
The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.

The Interface Declaration

At minimum, the interface declaration contains the Java keyword interface and the name of the interface that you are creating:
interface Countable {
    . . .
}
Note: By convention, interface names begin with capital letters just like class names do. Often, interface names end with "able" or "ible".

An interface declaration can have two other components: the public access specifier and a list of "superinterfaces". (An interface can extend other interfaces just as a class can extend or subclass another class.) Thus, the full interface declaration can look like this:

[public] interface InterfaceName [extends listOfSuperInterfaces] {
    . . .
}
The public access specifier indicates that the interface can be used by any class. If you do not specify that your interface is public, then your interface will only be accessible to classes that are defined in the same package as the interface.

The extends clause is similar to the extends clause in a class declaration, however, an interface can extend multiple interfaces (while a class can only extend one), and an interface cannot extend classes. The list of superinterfaces is a comma-delimited list of all of the interfaces extended by the new interface.

The Interface Body

The interface body contains the method signatures for all of the methods within the interface. In addition, an interface can contain constant declarations.
interface Countable {
    final int MAXIMUM = 500;

    void incrementCount();
    void decrementCount();
    int currentCount();
    int setCount(int newCount);
}
Each method signature is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. All of the methods declared within the interface body are implicitly abstract.


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces