Any way to extend two or more classes in java?

前端 未结 12 1464
再見小時候
再見小時候 2021-01-17 02:20

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

12条回答
  •  攒了一身酷
    2021-01-17 02:51

    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).

提交回复
热议问题