I'm practicing Java now and trying to dive into generics. I want to make this code work:
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;
}
}
Now I want to make a method which will be using objects of TwoD and ThreeD but not FourD. I've tried that:
static void showXYZsub(Coords<? super FourD> c) {
System.out.println("X Y Z:");
for (int i = 0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " + c.coords[i].y +
" " + c.coords[i].z);
System.out.println();
}
but I got an error "z cannot be resolved or is not a field".
As far I know, keyword super should filter object of any class which extending FourD, and FourD itself, but even if I'd change FourD to ThreeD or TwoD, the error will be the same.
I.e. if I use super only TwoD fields are visible, but in case of extends everything works fine.
Is Coords class have problem or what? Please help.
And sorry for engrish.
---edit: calling for 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);