I know that Java does not allow us to extend more than one class. I know that interfaces also exist and I don\'t want to use them this time. Is there some kind of trick or w
You can use a lookup of capabilities.
class Vehicle {
T lookup(Class klazz) {
return map.get(klazz); // typically
}
}
interface Flyable {
void fly();
}
Vehicle x;
Flyable f = x.lookup(Flyable.class);
if (f != null) {
f.fly();
}
This decouples classes. It requires runtime checking though.
It uses delegation: local members implementing the lookup'ed class/interface.
Advantage:
You can derive a class from Vehicle that can both fly (Flyable) and dive (Diving). The flying can be implemented by an instance of a shared class. You can even dynamically compose capabilities (add wheels to a boat).
That often is better than implementing several interfaces, where fly()
would either be a code copy, or delegate to a Flyable field (with shared implementation class).
Especially with multiple interfaces/classes involved you otherwise risk code on base class objects (Vehicle here) with cases and unsafe casts, forgetting if (x instanceof Boat)
.