[英]Nested extends in generics
I have three classes: 我有三个班:
class ClassR {}
class ClassA<T extends ClassR>{}
class ClassB<E extends ClassA<T extends ClassR>> extends ClassA<T> {
void foo(T param) {
}
void bar(E param) {
}
}
The third class does not compile unless I change it to 除非我将其更改为,否则第三个类不会编译
class ClassB<E extends ClassA<T>, T extends ClassR> extends ClassA<T> {
void foo(T bar) {
}
void bar(E param) {
}
}
Is there a way to keep only E parameter I need to pass when creating ClassB, and T being inferred? 有没有办法只保留创建ClassB时需要传递的E参数,并且推断T? For example, it would be convenient to use: 例如,使用方便:
new ClassB<ClassA<ClassR>>()
instead of: 代替:
new ClassB<ClassA<ClassR>, ClassR>()
This even simpler approach might work for you: 这种更简单的方法可能适合您:
class ClassR {}
class ClassA<T extends ClassR>{}
class ClassB<T extends ClassR> extends ClassA<T> {
void foo(T bar) {
}
void bar(ClassA<T> param) {
}
}
And usage then bypasses any reference to ClassA
to become: 然后用法绕过对ClassA
任何引用变为:
class SubR extends ClassR {}
ClassB<SubR> obj = new ClassB<SubR>();
Not sure if this is the answer you want but surely the simplest version reads: 不确定这是否是你想要的答案,但最简单的版本肯定是:
class ClassR {
}
class ClassA<T extends ClassR> {
}
class ClassB<T extends ClassR> extends ClassA<T> {
void foo(T bar) {
}
}
public void test() {
ClassB<ClassR> classB = new ClassB<>();
}
As type E
extends ClassA
you can safely omit the ClassA
type parameter in its declaration. 由于类型E
扩展了ClassA
您可以在其声明中安全地省略ClassA
类型参数。
Proper ClassA
type parameter is enforced in the second parameter to ClassB
. 在ClassB
的第二个参数中强制执行适当的ClassA
类型参数。
See below code for illustration : 请参阅以下代码以进行说明
class ClassB<E extends ClassA, T extends ClassR> extends ClassA<T> {
private ClassA ob;
public ClassB(E e, T t) {
super(t);
ob = e;
}
}
Usage sample: 使用范例:
class ClassR {
public ClassR() {};
}
class ClassS extends ClassR {
private int x;
public ClassS(int x) {
super();
this.x = x;
}
}
public static void test() {
ClassS data1 = new ClassS(1);
ClassB <ClassB, ClassS> first = new ClassB<>(null, data1);
ClassS data2 = new ClassS(2);
ClassB <ClassB, ClassS> second = new ClassB<>(first, data2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.