[英]Java: incompatible return type with a class implementing an interface
我有一个接口和一个实现:
// there are things
public interface Thing { /* ... */ }
// balls are things
public class Ball implements Thing { /* ... */ }
我有另一个接口和另一个实现:
// a dog can fetch any thing
public interface Dog {
public Thing fetch();
}
// a shepherd can fetch only a ball
public class Shepherd implement Dog {
public Ball fetch() { /* ... */ }
}
这可以。
但现在我想使用Ball
作为参数化类的参数:
public interface Dog {
public List<Thing> fetchList();
}
public class Shepherd implement Dog {
public List<Ball> fetchList() { /* ... */ }
}
Java 不允许我这样做,它说我正在尝试使用不兼容的类型。
同时,这种结构没有任何问题:
public class Shepherd implement Dog {
public List<Thing> fetchList() { /* ... */ }
}
为什么 Java 允许我使用接口的实现作为返回值的定义,但不允许我将它用作参数化类的参数?
提前致谢!
因为不是每一个Thing
是一个Ball
您可以尝试像这样参数化超类型
public interface Dog<T extends Thing> {
public List<T> fetchList();
}
public class Shepherd implement Dog<Ball> {
public List<Ball> fetchList() { /* ... */ }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.