【发布时间】:2015-04-17 00:02:33
【问题描述】:
我有一个名为Point 的类,其方法neighbors() 返回一个Points 数组:
public class Point {
public Point[] neighbors() { /* implementation not shown */ }
}
我有一个Point 的子类,称为SpecialPoint,它覆盖neighbors() 以返回SpecialPoints 的数组而不是Points。我认为这称为协变返回类型。
public class SpecialPoint extends Point {
public SpecialPoint[] neighbors() { /* implementation not shown */ }
}
在一个单独的类中,我想将Point 和SpecialPoint 与泛型一起使用
public <P extends Point> P doStuff(P point) {
P[] neighbors = point.neighbors();
// more stuff here including return
}
这不会编译,因为编译器只能保证P 是Point 的某个子类,但不能保证Point 的每个子类都会覆盖neighbors() 以返回其自身的数组我碰巧用SpecialPoint完成了,所以Java只知道P#neighbors()返回Point[],而不是P[]。
如何保证每个子类都使用协变返回类型覆盖 neighbors(),以便我可以将它与泛型一起使用?
【问题讨论】:
-
P可以是接口吗?