4. Interfaces

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

4.1.1. Advantages

  • capturing similarities between unrelated classes without forcing a class relationship;

  • declaring methods that one or more classes are expected to implement;

  • revealing an object's programming interface without revealing its class (objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers).

The interface declaration and the interface body:

interfaceDeclaration {
    interfaceBody
}

4.2.1. The interface Declaration

[public] interface InterfaceName [extends listOfSuperInterfaces] {
     . . .
}
interface Collection {
   int MAXIMUM = 500;
   void add(Object obj);
   void delete(Object obj);
   Object find(Object obj);
   int currentCount();
}

4.2.2. Multiple Extensions (Inheritance)

An interface can extend multiple interfaces (while a class can only extend one), and an interface cannot extend classes.

Audio in Portuguese

To use an interface, you write a class that implements the interface.

Definition: To implement an interface a class has to provides a method implementation for all of the methods declared within the interface.

class FIFOQueue implements Collection {
   . . .
   void add(Object obj) { . . . }
   . . .
}

An interface is 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:

interface CellAble {
   void draw();
   void toString();
   void toFloat();
}

class Row {
   . . .
   private CellAble[] contents;
   . . .
   void setObjectAt(CellAble ca, int index) {
      . . .
   }
   . . .
}

Any object that implemented the CellAble interface can be contained in the contents array and can be passed into the setObjectAt() method.

Audio in Portuguese