Skip to content
aaron-ljx edited this page Sep 13, 2020 · 4 revisions

Why Interfaces?

A class can only inherit from one parent class, but a class can inherit from multiple interfaces. This makes interfaces a great choice if you require multiple functionalities in your class.

Things to note

  1. Interfaces cannot be instantiated and all methods in interfaces are implicitly public.
  2. Methods in interfaces are only declared. The implementation is done in the class that inherits from the interface.
  3. ALL methods declared in the interface must be implemented.
  4. From Java 8 onward, it is possible to implement default methods in the interface.

Naming convention

Interfaces names should generally be adjectives. For example, Serializable or Clonable. In some cases, names can also be a noun when they represent a family of classes.

Example usage

interface Animal {
    void eat();
    default void jump() {
        System.out.println("jump");
    }
}

interface Upgradable {
    void fly();
}

class Dog implements Animal, Upgradable {

    @Override
    public void eat() {
        System.out.println("dog eating");
    }

    @Override
    public void fly() {
        System.out.println("dog flying");
    }
}

class Pig implements Animal, Upgradable {

    @Override
    public void eat() {
        System.out.println("pig eating");
    }

    @Override
    public void fly() {
        System.out.println("pig flying");
    }
}

public class Main {
     public static void main(String[] args) {
        Pig p = new Pig();
        Dog d = new Dog();

        p.eat();
        d.eat();

        p.fly();
        d.fly();
    }
}

Output: 
    pig eating
    dog eating
    pig flying
    dog flying
Clone this wiki locally