Interfaces

An interface defines a capability through method signatures. A class uses implements to promise that it provides those methods.

Interfaces keep callers independent of one class hierarchy. A Song, Podcast, and Video could all be Playable without sharing a superclass.

Describe a capability

interface Playable {
    int duration();
}

class Song implements Playable {
    @Override
    public int duration() {
        return 240;
    }
}

public class Main {
    public static void main(String[] args) {
        Playable track = new Song();
        System.out.println(track.duration());
    }
}

Output:

240

The variable has type Playable, so the caller depends only on the duration contract.

An implementing method cannot reduce visibility. Interface methods are public, so the implementation here must also be public.

Make Phone implement Chargeable and have it report an 85 percent charge.