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 2 - 7.
  • At line 6 a method is declared. This method must be declared in each class that implements the interface.
  • At line 9 and 18 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 execute.