Interfaces and Abstract Classes

Nathan Sprague

Toys

Recall our toy class hierarchy (now with volume!).

What is wrong with this design?

Improvement…

Two Key Benefits

Cell Phone

A cell phone is not a toy, but it does share some functionality…

public class CellPhone {
    private int chargeLevel;
    private int volume;

    public CellPhone(int chargeLevel, int volume) {
        this.chargeLevel = chargeLevel;
        this.volume = volume;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public void makeCall() {
        System.out.println("Riing... Hello.");
    }

    public void recharge() {
        chargeLevel = 10;
        System.out.println("All charged up!");
    }

}

Will this compile?

    public static void muteAll(ArrayList<LoudToy> toys) {
        for (LoudToy current : toys) {
            current.setVolume(0);
        }
    }

    public static void main(String[] args) {
        ArrayList<LoudToy> items = new ArrayList<>();
        
        ToySheep sheep = new ToySheep();
        CellPhone phone = new CellPhone(3, 4);
        
        items.add(sheep);
        items.add(phone);
        
        muteAll(items);
    }

Interfaces

Now, this will work:

    public static void muteAll(ArrayList<Audible> items) {
        for (Audible current : items) {
            current.setVolume(0);
        }
    }

    public static void main(String[] args) {
        ArrayList<Audible> items = new ArrayList<>();
        
        ToySheep sheep = new ToySheep();
        CellPhone phone = new CellPhone(3, 4);
        
        items.add(sheep);
        items.add(phone);
        muteAll(items);
    }

Multiple Implementation

Java classes can only extend one class, but they can implement multiple interfaces:

UML