10.8 Interfaces

In Java, a class can inherit directly from only one class; that is, a class can extend only one class. To allow a class to inherit behavior from multiple sources, Java provides the interface. Interfaces are often used to provide a specification for performing common tasks. They can also be used to promote code reusability.

An interface typically specifies behavior that a class will implement.

Interface members can be any of the following:

  • constants

  • methods

  • classes

  • other interfaces

To define an interface, we use the following syntax:

accessModifier interface InterfaceName
{
    // body of interface
}

Like classes, the Java convention is to name interfaces starting with a capital letter and capitalizing internal words.

Get Java Illuminated, 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.