java generics, how to extend from two classes?

后端 未结 3 1928
北荒
北荒 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:41

    A simple way for this problem is inheritance.

    public class A { // some codes }
    
    public class B extends A { }
    
    <T extends A>
    
    0 讨论(0)
  • 2021-01-27 05:43

    In java you cannot have a class which extends from two classes, since it doesn't support multiple inheritance. What you can have, is something like so:

    public class A
    ...
    
    public class B extends A
    ...
    
    public class C extends B
    ...
    

    In your generic signature, you can then specify that T must extend C: <T extends C>.

    You could give a look at Default Methods (if you are working with Java 8), which essentially are methods declared within interfaces, and in Java, a class can implement multiple interfaces.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题