Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


Creating and Using Interfaces

Interfaces provide a mechanism that allow hierarchically unrelated classes to implement the same set of methods. Basically, an interface is a collection of method definitions and constant values that is free from dependency on a specific class or class hierarchy. Interfaces are useful for: For example, suppose you were writing a spreadsheet program. The spreadsheet would contain a tabular set of cells. Each cell can contain one value. One approach to writing the spreadsheet would be to create a class called CellValue that represented a value that could be contained in one of the spreadsheet's cells. Another more generic approach would be to create an interface, say CellValue, that defined the list of methods that a "cell value" must implement: convertToFloat(), draw(), format(), and so on. Then the spreadsheet cells could contain any type of object that implemented the CellValue interface (or in other words implemented the list of methods). CellValues would not have to be hierarchically related.

Often, interfaces are touted as an alternative to multiple inheritance. However, multiple inheritance and interfaces actually provide very different functionality. [PENDING: maybe say more here]

In Java, an interface is another complex data type and interface names can be used in many of the same places where a type can be used (such as in method arguments and variable declarations).

Creating an Interface

Creating 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.

Using an 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).
[PENDING: is there more to say about interfaces. This whole section seems a bit anemic to me.]


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces