Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

8.4 Choosing — implementing several interfaces

Lesson

Many capabilities, one class

Because interfaces carry no state, a class can implement several at once — just list them, separated by commas. The class must then provide every method of every interface. Each interface is a separate type, so the same object can be used as any of them.


Worked example

class Tag implements Printable, Sized {
    public String label() { return "<" + text + ">"; }   // from Printable
    public int size() { return text.length(); }         // from Sized
}

Tag t = new Tag("hello");
Printable p = t;   // a Tag is a Printable
System.out.println(p.label());   // <hello>

The same Tag object can be seen as a Printable, a Sized, or a Tag.


▶ Try it: run this — Tag fulfills both contracts and can be referenced through either.



To implement two interfaces, you write...


A class implementing two interfaces must provide...


Type exactly what this program prints.

interface Printable { String label(); }
interface Sized { int size(); }
class Tag implements Printable, Sized {
    public String label(){ return "tag"; }
    public int size(){ return 3; }
}
public class Main { public static void main(String[] a){
    Tag t = new Tag();
    System.out.println(t.label());
    System.out.println(t.size());
}}

If Tag implements Printable, then Printable p = new Tag(...) is...


True or false?