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


Using an Interface as a Type

As mentioned previously, 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 primitive data type name or any other reference data type name.

Consider the spreadsheet problem introduced on Creating and Using Interfaces. Let's say that you defined an interface named CellAble that looked something like this:

interface CellAble {
    void draw();
    void toString();
    void toFloat();
}
Now, suppose that you had a row and column object that contained a bunch of objects that implemented the CellAble interface. Your Row class's setObjectAt() method could look like this:
class Row {
    private CellAble[] contents;
    . . .
    void setObjectAt(CellAble ca, int index) {
        . . .
    }
    . . .
}
Note the use of the interface name CellAble in the member variable declaration for contents and the method parameter declaration for ca. Any object that implemented the CellAble interface, regardless of where it existed within the class hierarchy, could be contained in the contents array and could be passed into the setObjectAt() method.


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