Sub topic 11
Interfaces That Extend Other Interfaces
In earlier chapters you wrote interfaces and had classes implement them. An interface can also build on another interface. This chapter shows how that works, why it is useful, and which mistakes to avoid.
What It Means for an Interface to Extend Another
Interface inheritance means one interface takes all the abstract methods of another interface and adds its own. The new interface is called the child interface, or subinterface. The interface it builds on is called the parent interface, or superinterface.
You write this with the extends keyword, the same word a class uses to extend another class:
interface Animal {
String sound();
}
interface Pet extends Animal {
String owner();
}The Pet interface now has two abstract methods. It declares owner() itself and gets sound() from Animal. Any class that implements Pet must supply both.
Why do this?
- Reuse. You write the shared methods once, in the parent.
- Layers of ability. Small interfaces describe small abilities, and a bigger interface combines them.
- Flexible references. Code that only needs the basic ability can ask for the parent type. Code that needs more can ask for the child type.
A Full Worked Example
Here a child interface combines two parent interfaces. Unlike a class, an interface can extend more than one interface. You list the parents after extends, separated by commas.
interface Viewable {
String view();
}
interface Editable {
void edit(String text);
}
interface Document extends Viewable, Editable {
void clear();
}
class Notebook implements Document {
private final StringBuilder pages = new StringBuilder();
@Override
public String view() {
return pages.toString();
}
@Override
public void edit(String text) {
pages.append(text);
}
@Override
public void clear() {
pages.setLength(0);
}
}
public class Main {
static void show(Viewable v) {
System.out.println("Showing: [" + v.view() + "]");
}
public static void main(String[] args) {
Notebook nb = new Notebook();
Document doc = nb;
doc.edit("Hello");
doc.edit(", world");
Editable e = nb;
e.edit("!");
show(nb); // prints: Showing: [Hello, world!]
doc.clear();
show(doc); // prints: Showing: []
}
}Here is what happens, step by step:
Documentextends bothViewableandEditable, so it holds three abstract methods:view(),edit(String), andclear().Notebookimplements onlyDocument. It still counts as aViewableand anEditable, becauseDocumentextends them.Notebookmust implement all three methods. If you leave one out, the code does not compile.- The same
Notebookobject is used through three reference types:Document,Editable, andViewable. - The
showmethod asks only for aViewable. It cannot calleditorclear, and it does not need to. This keeps the method simple and safe.
In the diagram, a solid arrow means "extends" and a dashed arrow means "implements."
Which Keyword Goes Where?
Beginners often mix up extends and implements. This table sums up the rules.
| What you declare | Its parent is | Keyword | How many parents |
|---|---|---|---|
| A class | A class | `extends` | One only |
| A class | An interface | `implements` | Many |
| An interface | An interface | `extends` | Many |
| An interface | A class | Not allowed | None |
Put simply: an interface never uses implements, and an interface can never extend a class.
Chains of Interfaces
Interface inheritance can go more than one level deep. Each level adds to everything above it.
interface Animal {
String sound();
}
interface Pet extends Animal {
String owner();
}
interface ServiceDog extends Pet {
String task();
}
class GuideDog implements ServiceDog {
@Override
public String sound() {
return "Woof";
}
@Override
public String owner() {
return "Sam";
}
@Override
public String task() {
return "guiding";
}
}
public class Main {
public static void main(String[] args) {
GuideDog g = new GuideDog();
Animal a = g;
Pet p = g;
System.out.println(a.sound()); // prints: Woof
System.out.println(p.owner() + " owns this pet"); // prints: Sam owns this pet
System.out.println(g instanceof Animal); // prints: true
}
}GuideDog implements only ServiceDog, but it must supply all three methods from the chain. The instanceof check confirms that a GuideDog counts as an Animal too.
When Two Parents Declare the Same Method
A child interface can extend two parents that declare the very same abstract method. This is fine. Neither parent has a body for the method, so there is nothing to clash. The implementing class just writes the method once.
interface Named {
String name();
}
interface Labeled {
String name();
}
interface Tag extends Named, Labeled {
}
class Badge implements Tag {
@Override
public String name() {
return "Guest";
}
}
public class Main {
public static void main(String[] args) {
Badge b = new Badge();
Named n = b;
Labeled l = b;
System.out.println(n.name() + " / " + l.name()); // prints: Guest / Guest
}
}The Tag interface adds no methods of its own, and that is allowed. An empty child interface is a way to give a combination of abstilities a single name.
Interface Inheritance in the Java Library
The Java standard library uses this idea everywhere. For example, java.util.List extends Collection, and Collection extends Iterable. That chain is why any List can be used in a for-each loop: the loop needs an Iterable, and every List is one.
Exercises
Exercise
Write an interface Shape with a method double area(), and an interface Solid that extends Shape and adds double volume(). Then write a class Cube with a side field that implements Solid. Which methods must Cube implement?
Show answer
interface Shape { double area(); } and interface Solid extends Shape { double volume(); }. Then class Cube implements Solid { private final double side; Cube(double side) { this.side = side; } public double area() { return 6 * side * side; } public double volume() { return side * side * side; } }. Cube must implement both area() and volume(), because Solid inherits area() from Shape.
Exercise
Will this compile? interface Flyer { void fly(); } and interface Bird implements Flyer { void sing(); }. If not, how do you fix it?
Show answer
No. An interface cannot use implements. Change it to interface Bird extends Flyer { void sing(); }.
Exercise
An interface C extends interfaces A and B. Both A and B declare void run(); with no body. A class Task implements C. How many times must Task write the run() method?
Show answer
Once. The two declarations match and neither has a body, so one public run() method in Task satisfies both A and B.