Skip to lesson

Implement several interfaces

A class can extend only one class, but it can implement any number of interfaces: class SmartPhone implements Camera, MusicPlayer. The object then fits wherever any of those types is needed.

One class, many interfaces

A smartphone is a camera and a music player at once. List the interfaces after implements, separated by commas: class SmartPhone implements Camera, MusicPlayer. The class must write every method of every interface in the list.

Example 1 · One class, two interfaces

PhoneDemo.javaJava
interface Camera {    void click();}
interface MusicPlayer {    void play(String song);}
class SmartPhone implements Camera, MusicPlayer {    public void click() {        System.out.println("Photo taken");    }
    public void play(String song) {        System.out.println("Playing " + song);    }}
public class PhoneDemo {    public static void main(String[] args) {        SmartPhone phone = new SmartPhone();        phone.click();        phone.play("Kesariya");    }}
Output
Photo taken
Playing Kesariya

What this code does

  • implements Camera, MusicPlayer signs two contracts at once, so the class writes both methods.
  • Through a SmartPhone variable, every method of the class can be called.

Example 2 · One object, many views

ViewsDemo.javaJava
interface Camera {    void click();}
interface MusicPlayer {    void play(String song);}
class SmartPhone implements Camera, MusicPlayer {    public void click() { System.out.println("Phone: photo taken"); }    public void play(String song) { System.out.println("Phone: playing " + song); }}
class DigitalCamera implements Camera {    public void click() { System.out.println("Camera: photo taken"); }}
public class ViewsDemo {    static void takeSelfie(Camera c) {        c.click();    }
    static void startMusic(MusicPlayer m) {        m.play("Lofi beats");    }
    public static void main(String[] args) {        SmartPhone phone = new SmartPhone();        takeSelfie(phone);        startMusic(phone);        takeSelfie(new DigitalCamera());    }}
Output
Phone: photo taken
Phone: playing Lofi beats
Camera: photo taken

What this code does

  • The same phone is passed as a Camera and as a MusicPlayer. It is one object with two types.
  • takeSelfie works with any camera, including a DigitalCamera that cannot play music.

Example 3 · Mistake: calling outside the view

ViewErrorDemo.javaJava
interface Camera {    void click();}
interface MusicPlayer {    void play(String song);}
class SmartPhone implements Camera, MusicPlayer {    public void click() { System.out.println("Photo taken"); }    public void play(String song) { System.out.println("Playing " + song); }}
public class ViewErrorDemo {    public static void main(String[] args) {        Camera c = new SmartPhone();        c.click();        c.play("Kesariya");    }}
Sample compiler output
ViewErrorDemo.java:18: error: cannot find symbol
        c.play("Kesariya");
         ^
  symbol:   method play(String)
  location: variable c of type Camera
1 error

What this code does

  • The object can play music, but the variable is a Camera. Through it, only Camera methods are visible.
  • Fix: use a MusicPlayer or SmartPhone variable for play. The reference type decides what you may call.

The same object can be stored in a Camera variable or a MusicPlayer variable. Each variable is a different view of one object: through Camera c, only camera methods can be called, even though the object can also play music.

extends and implements together

A college app has a Student class, and Rohan is also an athlete and a singer. Write extends first, then implements: class StudentAthlete extends Student implements Athlete, Singer.

Example 4 · extends and implements together

StudentAthleteDemo.javaJava
class Student {    protected String name;
    Student(String name) {        this.name = name;    }
    void study() {        System.out.println(name + " is studying");    }}
interface Athlete {    void playSport();}
interface Singer {    void sing();}
class StudentAthlete extends Student implements Athlete, Singer {    StudentAthlete(String name) {        super(name);    }
    public void playSport() {        System.out.println(name + " is playing kabaddi");    }
    public void sing() {        System.out.println(name + " is singing");    }}
public class StudentAthleteDemo {    public static void main(String[] args) {        StudentAthlete r = new StudentAthlete("Rohan");        r.study();        r.playSport();        r.sing();    }}
Output
Rohan is studying
Rohan is playing kabaddi
Rohan is singing

What this code does

  • extends Student comes first and gives the field name and the method study. implements Athlete, Singer adds two abilities.
  • Rohan is a Student, an Athlete and a Singer at once, but has only one parent class.

This answers the question from Why a class can extend only one class (opens in a new tab): extend the main class, and add each extra role as an interface. The header has one fixed shape, and javac stops every other shape.

Fix the error

Fix the class header

Read the error, then pick the line that fixes it.

Round 1 of 4

Duck should be a Bird that can also swim.

class Bird { }
interface Swimmer { void swim(); }
class Duck implements Swimmer extends Bird {
public void swim() { System.out.println("Paddle"); }
}

Error

Duck.java:3: error: '{' expected

An interface can extend interfaces

Interface inheritance is when an interface uses extends to build on one or more other interfaces, as in interface SmartWatch extends Chargeable, Connectable. It collects all their methods, and a class implementing it must write them all.

A fitness band can be charged and connected, and it also shows the time. interface SmartWatch extends Chargeable, Connectable collects both contracts and adds showTime().

Example 5 · An interface that extends two interfaces

WatchDemo.javaJava
interface Chargeable {    void charge();}
interface Connectable {    void connect(String device);}
interface SmartWatch extends Chargeable, Connectable {    void showTime();}
class FitBand implements SmartWatch {    public void charge() { System.out.println("Charging band"); }    public void connect(String device) { System.out.println("Connected to " + device); }    public void showTime() { System.out.println("10:30 AM"); }}
public class WatchDemo {    static void chargeAll(Chargeable[] items) {        for (Chargeable c : items) {            c.charge();        }    }
    public static void main(String[] args) {        SmartWatch band = new FitBand();        band.connect("Priya's phone");        band.showTime();        chargeAll(new Chargeable[] { band });    }}
Output
Connected to Priya's phone
10:30 AM
Charging band

What this code does

  • SmartWatch uses extends to collect the methods of two interfaces and adds showTime. FitBand must write all three.
  • A FitBand is also a Chargeable, so it fits in a Chargeable[] array with any other chargeable thing.

A class that implements SmartWatch must write every method of the whole chain. In return, its objects are also Chargeable and Connectable. An interface cannot extend a class: classes have fields and bodies, and an interface builds only on other contracts.

Multiple inheritance of type, without the diamond

Multiple inheritance of type means one class can have many types, one for each interface it implements, while it gets fields and method bodies from only one parent class.

Why a class can extend only one class (opens in a new tab) showed the diamond problem: two parents giving two bodies. A washer-dryer gets void start(); from both Washer and Dryer, yet nothing clashes.

Example 6 · Same method in two interfaces: no diamond problem

WasherDryerDemo.javaJava
interface Washer {    void start();    int waterLitres();}
interface Dryer {    void start();    int heatLevel();}
class WasherDryer implements Washer, Dryer {    public void start() {        System.out.println("Washing, then drying");    }
    public int waterLitres() { return 50; }
    public int heatLevel() { return 3; }}
public class WasherDryerDemo {    public static void main(String[] args) {        WasherDryer wd = new WasherDryer();        Washer w = wd;        Dryer d = wd;        w.start();        d.start();        System.out.println(w.waterLitres() + " L, heat " + d.heatLevel());    }}
Output
Washing, then drying
Washing, then drying
50 L, heat 3

What this code does

  • Both interfaces declare void start(); with no body. The class writes one start that keeps both promises.
  • Through either view, the same body runs. There is no second body to clash with, so there is no diamond problem.

A plain interface method has no body, and an interface has no normal fields. So the class writes one start() that keeps both promises, and there is nothing to choose between. Constants with the same name are no clash either: write Washer.MAX or Dryer.MAX (the plain name gives reference to MAX is ambiguous).

Interface methods with a body (default methods) bring back one small clash. default, static and private methods (opens in a new tab) shows Java's rule for it.

Next step

Check your understanding

12 quick questions