Interfaces

index
STYLE
 "Write to an interface, not to an implementation."

What this rule means is that you should use an interface to describe the essential methods of a class, then use only those methods. This gives you the freedom to implement the same interface in different ways for different needs.

For example, you might write a Displayable interface for displaying graphical information, and implement it one way for displaying information on the screen, another way for saving it on a file.

Whenever two or more classes share some behavior, and need to be treated interchangeably for some purposes, you probably should define that behavior in an interface. For example, many kinds of objects in the Java API can be sorted; to make this possible, those objects implement the Comparable interface.

An interface, like a class, should have a name beginning with a capital letter, and should typically be in a file of its own. Interface names should typically be adjectives.

INTERMEDIATE

The syntax is

accessType interface Name { ... }

where accessType must be either public or unspecified ("package"). The interface may contain constants and may declare (but not define) methods.

All variables declared within an interface are automatically have public access and are static and final (that is, constants), and must be initialized. You may use or omit the keywords public, static, and final.

Methods are declared but not defined; that is, no body is provided. Here is an example declaration:

void barGraph(double[][] numbers);

All methods declared within an interface are automatically public and abstract. You may use or omit the keywords public and abstract.

Interfaces are implemented by zero or more classes, which means that they must supply definitions for all the declared methods. For example, if the above abstract method is declared in an interface Displayable, an implementing class might look like

class NumberCruncher implements Displayable {
    ...
    void barGraph(double[][] numbers) {
        // ... actual code...
    }
    ...
}

An interface is a type. Hence, variables and methods may be declared as being of that type. For example,

Displayable fileDisplay = new Displayable(System.out);
showAll(fileDisplay);

Objects can only be created from fully defined classes. Interfaces, being incomplete, cannot be instantiated.

ADVANCED

An abstract class is intermediate between an interface and a class.