java泛型,如何从两个类扩展? [英] java generics, how to extend from two classes?
问题描述
我想要一个Class对象,但是我想强制使用它表示的任何类来扩展A类以及B类. 我能做
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
<T extends ClassA & ClassB>
但是不可能从两个类都进行扩展,有没有办法做到这一点?
but it is not possible to extend from both classes, Is there a way to do this?
推荐答案
在Java中,您不能拥有从两个类扩展的类,因为它不支持多重继承.您可以拥有的是这样的:
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
...
然后,在通用签名中,可以指定T
必须扩展C
:<T extends C>
.
In your generic signature, you can then specify that T
must extend C
: <T extends C>
.
您可以看一下 Default Methods
(如果您使用的是Java 8)(本质上是在接口中声明的方法),那么在Java中,一个类可以实现多个接口.
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.
这篇关于java泛型,如何从两个类扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!