![](/img/trans.png)
[英]Java generics: Bound mismatch: The type is not a valid substitute for the bounded parameter of the type
[英]java generics Bound mismatch: The type is not a valid substitute for the bounded parameter
public class XYZ {
public static void main(String[] args) {
C<A> c = new D<A>();
我收到一个错误:::绑定不匹配:类型A不是有效替代参数<T扩展了C <T>类型的B <T >>。 我究竟做错了什么? }
}
class D<T extends B<T>> implements C<T>{
@Override
public void ok(T b) {
System.out.println(b.getId());
}
}
interface C<T extends B<T>>{
void ok(T b);
}
class A extends B<String>{
}
class B<T>{
private T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
您必须使用通配符B<?>
。 问题是C<T extends B<T>>
。 您将C和B的类型T
但是您声明C<A>
。 因此,在您的情况下, B
也将获得类型A
,但是您的代码说, class A extends B<String>
,其中B
必须是String
。 D
的相同问题。 希望我的答案是明确的。
以下代码将为您工作:
public static void main(String[] args) {
C<A> t = new D<A>();
}
static class D<T extends B<?>> implements C<T> {
@Override
public void ok(T b) {
System.out.println(b.getId());
}
}
interface C<T extends B<?>> {
void ok(T b);
}
static class A extends B<String> {
}
static class B<T> {
private T id;
public T getId() {
return id;
}
public void setId(T id) {
this.id = id;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.