Interfaces may extend other interfaces, and, like a class definition, an interface definition may include an extends clause. When one interface extends another, it inherits all the abstract methods and constants of its superinterface and can define new abstract methods and constants. Unlike classes, however, the extends clause of an interface definition may include more than one superinterface. For example, here are some interfaces that extend other interfaces:
public interface Positionable extends Centered {
void setUpperRightCorner(double x, double y);
double getUpperRightX();
double getUpperRightY();
}
public interface Transformable extends Scalable, Translatable, Rotatable {}
public interface SuperShape extends Positionable, Transformable {}
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:
An interface contains no implementation whatsoever. All methods of an interface are implicitly abstract and must have a semicolon in place of a method body. The abstract modifier is allowed but, by convention, is usually omitted. Since static methods may not be abstract, the methods of an interface may not be declared static .
An interface defines a public API. All members of an interface are implicitly public, and it is conventional to omit the unnecessary public modifier. It is an error to define a protected or private method in an interface.
An interface may not define any instance fields. Fields are an implementation detail, and an interface is a pure specification without any implementation. The only fields allowed in an interface definition are constants that are declared both static and final.
An interface cannot be instantiated, so it does not define a constructor.
Interfaces may contain nested types. Any such types are implicitly public and static. See Section 3.10 later in this chapter.