[英]How to subclass generics properly?
I have searched other questions/answers, an I'm still confused about this JAVA ISSUE. 我搜索了其他问题/答案,对此JAVA问题我仍然感到困惑。
If I want to subclass a type that takes generic parameters, how would I do so while using generic parameters for the subclass too without it getting shadowed? 如果我想对采用通用参数的类型进行子类化,那么在对子类也使用通用参数时又如何做到这一点呢?
For example: 例如:
public class A <T> extends ArrayList<T> {}
So if i instantiate my custom class, with say, Integers as the parameter, does it take that value as parameter for <T>
for the ArrayList part of it too? 因此,如果我实例化我的自定义类(例如说Integers作为参数),它是否也将该值作为ArrayList部分的
<T>
参数? If not, then how would I specify the type for the ArrayList? 如果没有,那么我将如何指定ArrayList的类型?
And I know sub classing containers may not be the best idea in many situations, but in this case I have decided it would be appropriate. 而且我知道在许多情况下子类化容器可能不是最好的主意,但在这种情况下,我认为这是合适的。
yes that would be how one goes about it. 是的,那将是如何做到的。
public static void main(String[] args) {
B<Integer> b = new B<Integer>();
b.a = 1;
b.b = "one";
b.add(1);
b.add(2);
}
public static class A<T> extends ArrayList<T> {
public T a;
}
public static class B<T> extends A<T> {
public T b;
}
if you like you could even have them have different types, as long as you supply the super-class with it's type as well: 如果您愿意,甚至可以让它们具有不同的类型,只要您也提供具有该类型的超类即可:
public static void main(String[] args) {
B<Integer, String> b = new B<Integer, String>();
b.a = 1;
b.b = "one";
b.add(1);
b.add(2);
}
public static class A<T> extends ArrayList<T> {
public T a;
}
public static class B<U, T> extends A<U> {
public T b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.