Nathan Sprague
Recall our toy class hierarchy (now with volume!).
What is wrong with this design?
Polymorphism: we can write code that will work with any descendent.
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!");
}
}
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);
}
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);
}
Java classes can only extend one class, but they can implement multiple interfaces: