使用Java中的泛型保证协变返回类型

时间:2015-04-16 13:56:05

标签: java generics

我有一个名为Point的类,其方法neighbors()返回Point的数组:

public class Point {
    public Point[] neighbors() { /* implementation not shown */ }
}

我有一个Point的子类,名为SpecialPoint,它会覆盖neighbors()以返回SpecialPoint s而不是Point的数组。我认为这被称为协变返回类型。

public class SpecialPoint extends Point {
    public SpecialPoint[] neighbors() { /* implementation not shown */ }
}

在另一个课程中,我想将PointSpecialPoint与泛型一起使用

public <P extends Point> P doStuff(P point) {
    P[] neighbors = point.neighbors();
    // more stuff here including return
}

这不会编译,因为编译器只能保证PPoint的某个子类,但不能保证Point的每个子类都会覆盖neighbors()当我碰巧使用SpecialPoint时,返回一个自己的数组,因此Java只知道P#neighbors()返回Point[],而不是P[]

我如何保证每个子类使用协变返回类型覆盖neighbors(),以便我可以将它与泛型一起使用?

2 个答案:

答案 0 :(得分:14)

您可以使用界面:

public interface Point<P extends Point<P>> {
    P[] neighbors();
}

public class SimplePoint implements Point<SimplePoint> {
    @Override
    public SimplePoint[] neighbors() { /* ... */ }
}

public class SpecialPoint implements Point<SpecialPoint> {
    @Override
    public SpecialPoint[] neighbors() { /* ... */ }
}

然后:

public <P extends Point<P>> P doStuff(P point) {
    P[] neighbors = point.neighbors();
    /* ... */
}

如果您仍然需要在实现之间分解代码,那么最好使用抽象类:

public abstract class Point<P extends Point<P>> {
    public abstract P[] neighbors();
    public void commonMethod() { /* ... */ }
}

public class SimplePoint extends Point<SimplePoint> { /* ... */ }

public class SpecialPoint extends Point<SpecialPoint> { /* ... */ }

答案 1 :(得分:0)

interface Point可能会解决您的问题:

public class Test  
{

    public interface Point  {
        public Point[] neighbors();
    }

    public class SpecialPoint implements Point {
        public SpecialPoint[] neighbors() { return null; }
    }

    public class SpecialPoint2  implements Point {
        public SpecialPoint2[] neighbors() { return null; }
    }

    public Point doStuff(SpecialPoint point) {
        Point[] neighbors = point.neighbors();
        return neighbors[0];
    }

    public Point doStuff(SpecialPoint2 point) {
        Point[] neighbors = point.neighbors();
        return neighbors[0];
    }
}