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

Creating and Using Interfaces

Sometimes, you'd like classes from different parts of the class hierarchy to behave in similar ways. For example, suppose you are writing a spreadsheet program which contains a tabular set of cells, each containing one value. You'd like to be able to put Strings, Floats, Dates, Integers, Equations, and so on into a cell in the spreadsheet. To do so, Strings, Floats, Dates, Integers, and Equations would all have to implement the same set of methods. One way to achieve this is to find the common ancestor of the classes and implement the methods you need there. However, this is not a practical solution, as Object is often the common ancestor. Except through Object, the objects you'd like to put in your spreadsheet cells are unrelated in the class hierarchy. But you are not allowed to modify Object.

One approach you could take 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. Then you could create a String, Float, Date, Integer, and Equation subclass of CellValue. In addition to being a lot of work, this approach arbitrarily forces a relationship on those classes that is otherwise unnecessary, and you must duplicate and re-implement classes that already exist.

Java provides a better way--through interfaces.

What Are Interfaces?

An interface is a collection of method definitions (without implementations) and constant values.

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 {
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 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).

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.

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