Card 06/ 08

GotchaDifficulty: Advanced1 min

Single Inheritance: One extends, Many implements

The compiler refuses a second parent class and accepts ten interfaces.

A Java class may extend exactly one class and implement any number of interfaces. Two parent classes could each bring fields and method bodies that clash; interfaces bring no fields, and the one clash they can cause, two default methods with the same signature, the compiler makes you resolve.

You have a class that should reuse the machinery in two abstract classes. The compiler refuses the second one, and the error does not explain why the same class may implement as many interfaces as it likes:

text
Report.java:3: error: '{' expected
class SalesReport extends Report, Scheduled {
                                ^

A class holds one copy of each of its fields. Two parents with a field of the same name would give an object two of them, and every read in the class would need a rule about which. Two parents with the same method and different bodies would need a rule too, and there is no good one.

Interfaces have neither problem, because they have no fields. Implement ten and the object gains no state at all. The one collision that can arise, two interfaces with the same default method, is a compile error, and you resolve it by overriding and saying which you meant:

java
class SalesReport extends Report implements Scheduled, Archivable, Exportable {
    @Override
    public String describe() {
        return Scheduled.super.describe();
    }
}

So extends is a scarce resource and implements is not. Spend the one extends on shared state and a fixed sequence, and express everything else as capabilities.