Skip to content
bingmeow1999 edited this page Nov 30, 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 and abstract.
  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

Let's practice! (read aboout PECS first maybe) Take A<: I, where A is a subclass of I where I is a interface.

Will is I i = new A(); be something possible to create? Go figure!

Ans: yes.

jshell> interface I {}
|  created interface I

jshell> class A implements I { A(){} }
|  created class A

jshell> I newthing = new A();
newthing ==> A@27fa135a
  • Think about it this way:
    • Even though we learned that an interface is purely abstract, and we are not able to create concrete methods or instance variables. BUT as seen above, we are able to create a new object of type I interface. We can think about this in the context of Instruments. If instruments is a category, you can take A() in as a type of instrument. For example, a trumpet. This trumpet is able to initialise to become A() which is a type of instrument.
Clone this wiki locally