Implementing Interfaces

Abstract Classes and Interfaces

Implementing Interfaces

🙋 Need help? Ask an expert now!

Java functions with "single inheritance", meaning that a subclass can only inherit from one superclass. The reserved word extends can only be used to extend from one class. However, Java has interfaces, a class that allows multiple inheritance. An interface is a set of requirements that a class must implement. An interface is a list of constants and method headers with no method bodies. All methods and constants must be implemented by the class. Let's see how an interface can be used.

InterfaceTestOne.java
package exlcode;

public interface InterfaceTestOne {

  int exampleVariableOne = -5;
  void print();
}
InterfaceTestThree.java
package exlcode;

public class InterfaceTestThree implements InterfaceTestOne, InterfaceTestTwo {

  // implements the method print() from InterfaceTestOne
  public void print() {
    System.out.println(exampleVariableOne);
  }

  // implements the method printGreeting() from InterfaceTestOne
  public void printGreeting() {
    System.out.println(exampleVariableTwo);
  }
}
InterfaceTestTwo.java
package exlcode;

public interface InterfaceTestTwo {

  String exampleVariableTwo = "Hello World!";
  void printGreeting();
}
InterfacesExample.java
package exlcode;

public class InterfacesExample {

  public static void main(String[] args) {
    InterfaceTestThree interfaceTestThree = new InterfaceTestThree();
    interfaceTestThree.print();
    interfaceTestThree.printGreeting();
  }
}

The Java reserved word implements is used instead of extends for interfaces. You are able to implement multiple interfaces by separating them with a comma. The class that implements an interface inherits the methods and the instance variables of the interface. However, similar to abstract classes, the methods have to be declared inside the class with a proper method body. The variables implemented in the interface do not necessarily have to be used in the class. In addition, methods from the interface must be declared public. All variables in an interface are public, static, and final by default.

Edit Me on GitHub!

Application Question

Which of the following statements regarding interfaces is false?