Previous | Next | Trail Map | Learning the Java Language | More Features of the Java Language

Creating Interfaces

The Java language supports interfaces that you use to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy.

What Is an Interface?

This section defines the term "interface," shows you an example of an interface and how to use it, and talks about why you may need interfaces in your programs.

Defining an Interface

Defining an interface is similar to creating a new class. An interface definition has two components: 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.

Implementing the Sleeper Interface

To use an interface, you write a class that implements the interface. When a class claims to implement an interface, the class is claiming that it provides a method implementation for all of the methods declared within the interface (and its superinterfaces).

Using an Interface as a Type

When you define a new interface you are in essence defining a new reference data type. You can use interface names anywhere you'd use any other type name: variable declarations, method parameters and so on.

Warning! Interface Cannot Grow

If you ship public interfaces to other programmers, here's a limitation of interfaces that you should be aware of: Interfaces cannot grow. Let's look at why this is the case.


Previous | Next | Trail Map | Learning the Java Language | More Features of the Java Language