Careeroza
Multiple Interfaces
One Class, Many Roles
Example
A smartphone is a camera, a phone and a music player at the same time. Each interface is a separate role.
public class Main {
public static void main(String[] args) {
SmartPhone phone = new SmartPhone();
phone.call("9876543210");
phone.click();
phone.play();
Camera cam = phone; // use only the Camera role
cam.click();
}
}
interface Phone { void call(String number); }
interface Camera { void click(); }
interface MusicPlayer { void play(); }
class SmartPhone implements Phone, Camera, MusicPlayer {
public void call(String number) { System.out.println("Calling " + number); }
public void click() { System.out.println("Photo captured"); }
public void play() { System.out.println("Playing music"); }
}Output
Calling 9876543210 Photo captured Playing music Photo captured
Default Method Conflict
Example
If two interfaces give the same default method, the class must override it and can pick one with Interface.super.method().
public class Main {
public static void main(String[] args) {
new Duck().move();
}
}
interface Swimmer {
default void move() { System.out.println("Swimming"); }
}
interface Flyer {
default void move() { System.out.println("Flying"); }
}
class Duck implements Swimmer, Flyer {
@Override
public void move() {
Swimmer.super.move();
Flyer.super.move();
System.out.println("Duck can do both");
}
}Output
Swimming Flying Duck can do both
Interfaces Extending Interfaces
interface Readable { String read(); }
interface Writable { void write(String data); }
// an interface can extend several interfaces
interface ReadWrite extends Readable, Writable { }
class FileStore implements ReadWrite {
private String data = "";
public String read() { return data; }
public void write(String d) { data = d; }
}