Interfaces

Inside Interfaces only methods can be defined.

The methods don't have body and must be declared in the classes that implement the interface.

Syntax

Defining interfaces:

Implementing interface:

Example

Output:

Explanation:

  • An interface is defined at lines 5 - 10.
  • At line 9 a method is declared. This method must be declared in each class that implements the interface.
  • At line 12 and 21 the classes Car and Bicycle implement the interface. For this reason they must define the function getInsuranceCost. If this is not done then the code won't compile.