Interface Basics

A Contract

An interface is a contract: a list of methods a class promises to provide. A class implements an interface and must give a body to every abstract method.

  • Methods without a body are implicitly public abstract.
  • Fields are implicitly public static final (constants).
  • An interface cannot be instantiated and has no constructors.
  • A class can implement many interfaces: class A implements X, Y.

Implementing an Interface

Example

public class Main {
    public static void main(String[] args) {
        Playable[] items = { new Song("Kesariya"), new Podcast("Tech Talk", 42) };
        for (Playable p : items) {
            p.play();
        }
        System.out.println("Max volume: " + Playable.MAX_VOLUME);
    }
}

interface Playable {
    int MAX_VOLUME = 100;        // public static final
    void play();                 // public abstract
}

class Song implements Playable {
    private final String title;
    Song(String title) { this.title = title; }
    @Override public void play() { System.out.println("Playing song: " + title); }
}

class Podcast implements Playable {
    private final String name;
    private final int episode;
    Podcast(String name, int episode) { this.name = name; this.episode = episode; }
    @Override public void play() { System.out.println("Playing podcast: " + name + " #" + episode); }
}

Output

Playing song: Kesariya
Playing podcast: Tech Talk #42
Max volume: 100

Note: Implementing methods must be public, because interface methods are public. Writing void play() without public in the class is a compile error.