Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

Interfaces

sebastianchristopher edited this page Sep 13, 2019 · 2 revisions

Interfaces

An interface is a group of methods multiple different classes may inherit. A class "implements an interface"; that is, the class needs to provide the methods of the interface that it implements. Interfaces allow us to separate what a class should be able to do in terms of functionality.

public interface Animal {

  void speak();

  void run();
}
// implements Animal
public class Dog {

  public void speak() {
    System.out.println("Woof!");
  }

  public void run(String name) {
    System.out.println(name + " is bounding!");
  }
// implements Animal
public class Horse {

  public void speak() {
    System.out.println("Neigh!");
  }

  public void run(String name) {
    System.out.println(name + " is galloping!");
  }

Interfaces are commonly likened to "contracts" that the developer "signs". Because whenever a class implements an interface it is obligated to include every method outlined in the interface. If it does not, the class won't even compile. Therefore, implementing an interface is like signing a contract saying you promise this class will contain every method listed in the interface.

  • Interface methods can only be and are by default abstract and public. They don't have method bodies, only the method signature.
  • Interface attributes can only be and are by default public, static and final.
  • They can't have constructors or create objects.
  • A class must implement all methods of an interface, unless the class is declared as abstract.
  • On implementation of an interface, you must override all of its methods (@Override annotation).

(https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)

Clone this wiki locally