带super关键字的Java泛型方法

带super关键字的Java泛型方法,java,generics,Java,Generics,我现在正在练习Java,并试图深入研究泛型。我想让这段代码正常工作: public class TwoD { // simple class to keep two coordinate points int x, y; TwoD(int a, int b) { x = a; y = b; } } public class ThreeD extends TwoD { //another simple class to extend Tw

我现在正在练习Java,并试图深入研究泛型。我想让这段代码正常工作:

public class TwoD { // simple class to keep two coordinate points
    int x, y;

    TwoD(int a, int b) {
        x = a;
        y = b;
    }
}

public class ThreeD extends TwoD { //another simple class to extend TwoD and add one more point
    int z;

    ThreeD(int a, int b, int c) {
        super(a, b);
        z = c;
    }
}
public class FourD extends ThreeD { //just like previous
    int t;

    FourD(int a, int b, int c, int d) {
        super(a, b, c);
        t = d;
    }
}
public class Coords<T extends TwoD> { //class to keep arrays of objects of any previous class
    T[] coords;

    Coords(T[] o) {
        coords = o;
    }
}

你试图做的是不可能的,因为当参数是二维点时,你将如何得到
点.z

你说

be using objects of TwoD and ThreeD but not FourD 
为什么要限制
FourD
对象? 通过继承,每个
FourD
都是
ThreeD
。因此,如果某个东西需要三个D,它也应该能够处理
FourD
s


请注意,这是有意义的:如果您的函数需要三维点,它将无法处理2D,因为它将缺少维度,但需要4D,没有问题,只需忽略多余的一个。

当您说
CoordsCan时,您还添加了调用showXYZsub方法的部分。
FourD fd[] = { 
new FourD(1, 2, 3, 4), new FourD(6, 8, 14, 8), new FourD(22, 9, 4, 9),
        new FourD(3, -2, -23, 17) };
Coords<FourD> fdlocs = new Coords<FourD>(fd);
showXYZsub(fdlocs);
Coords<? super FourD> c
Coords<? extends ThreeD> c
be using objects of TwoD and ThreeD but not FourD