Interfaces

Interfaces #

Java doesn’t support multiple inheritance becaouse of diamond problem. However Java has interfaces that can be used to achieve similar result.

Properties of Interfaces #

  • Interfaces can be implemented with implements keyword
  • A class can implement multiple interfaces
  • An interface can implement multiple interfaces
  • Interface cannot be instantiated
  • All of the methods in an interface are abstract

Example Interface #

interface Language {
   public Integer getNumberOfSpeakers();
   public String getFamily();
}

and then this interface can be implemented in a class.

class English implements Language {
  public Integer getNumberOfSpeakers() {
    return 1_500_000_000;
  }

  public String getFamily() {
    return "Indo-European";
  }
}

In this example if the class English does not implement all of the methods in the Language interface then an error will occur.