Card 06/ 08
All 8 cards
GotchaDifficulty: Advanced1 min
Why You Can Implement Ten Interfaces and Extend Exactly One Class
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.
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.
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.