Implement several interfaces
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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"); }}Photo taken Playing Kesariya
What this code does
implements Camera, MusicPlayersigns two contracts at once, so the class writes both methods.- Through a
SmartPhonevariable, every method of the class can be called.
Example 2 · One object, many views
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()); }}Phone: photo taken Phone: playing Lofi beats Camera: photo taken
What this code does
- The same
phoneis passed as aCameraand as aMusicPlayer. It is one object with two types. takeSelfieworks with any camera, including aDigitalCamerathat cannot play music.
Example 3 · Mistake: calling outside the view
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"); }}ViewErrorDemo.java:18: error: cannot find symbol
c.play("Kesariya");
^
symbol: method play(String)
location: variable c of type Camera
1 errorWhat this code does
- The object can play music, but the variable is a
Camera. Through it, onlyCameramethods are visible. - Fix: use a
MusicPlayerorSmartPhonevariable forplay. 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
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(); }}Rohan is studying Rohan is playing kabaddi Rohan is singing
What this code does
extends Studentcomes first and gives the fieldnameand the methodstudy.implements Athlete, Singeradds two abilities.Rohanis aStudent, anAthleteand aSingerat 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.
Error
Duck.java:3: error: '{' expectedAn 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
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 }); }}Connected to Priya's phone 10:30 AM Charging band
What this code does
SmartWatchusesextendsto collect the methods of two interfaces and addsshowTime.FitBandmust write all three.- A
FitBandis also aChargeable, so it fits in aChargeable[]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
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()); }}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 onestartthat 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).
Next step
Check your understanding
12 quick questions