Interfaces

Like a class, an interface defines a new reference type. Unlike classes, however, interfaces provide no implementation for the types they define. As its name implies, an interface specifies only an API: all of its methods are abstract and have no bodies. It is not possible to directly instantiate an interface and create a member of the interface type. Instead, a class must implement the interface to provide the necessary method bodies. Any instances of that class are members of both the type defined by the class and the type defined by the interface. Interfaces provide a limited but very powerful alternative to multiple inheritance .[9] Classes in Java can inherit members from only a single superclass, but they can implement any number of interfaces. Objects that do not share the same class or superclass may still be members of the same type by virtue of implementing the same interface.

Defining an Interface

An interface definition is much like a class definition in which all the methods are abstract and the keyword class has been replaced with interface. For example, the following code shows the definition of an interface named Centered. A Shape class, such as those defined earlier in the chapter, might implement this interface if it wants to allow the coordinates of its center to be set and queried:

public interface Centered {
    void setCenter(double x, double y);
    double getCenterX();
    double getCenterY();
}

A number of restrictions apply to the members of an interface: ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.