java generics, how to extend from two classes?

后端 未结 3 1959
北荒
北荒 2021-01-27 05:15

I want to have a Class object, but I want to force whatever class it represents to extend class A and also class B. I can do



        
3条回答
  •  耶瑟儿~
    2021-01-27 05:49

    Java does not have multiple inheritance as a design decision, but you may implement multiple interfaces.

    As of Java 8 these interfaces may have implementations.

    To use multiple classes there are other patterns:

    1. If the parent classes are purely intended for that child class, but handle entirely different aspects, and were therefore separated, place them in a single artificial hierarchy. I admit to doing this once.

    2. Use delegation; duplicate the API and delegate.

    3. Use a lookup/discovery mechanism for very dynamic behaviour.

      public T lookup(Class klazz);

      This would need an API change, but uncouples classes, and is dynamic.

提交回复
热议问题