Czesc. Przerabiam jedna ksiazke do Javy, jestem na generykach. Mam problem ze zrozumieniem jednego przykladu. Mam klasy 2d, 3d i 4d:
public class TwoD {
int x, y;
TwoD(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ThreeD extends TwoD {
int z;
ThreeD(int x, int y, int z) {
super(x, y);
this.z = z;
}
}
public class FourD extends ThreeD {
int v;
FourD(int x, int y, int z, int v) {
super(x, y, z);
this.v = v;
}
}
do tego klasa Coords
public class Coords<T extends TwoD> {
T[] coords;
Coords(T[] o) {
coords = o;
}
}
A na koncu BoundedWildcard, która sprawia problemy:
public class BoundedWildcard {
static void showXY(Coords<? extends TwoD> c) {
System.out.println("Wspolrzedne X Y:");
for (int i = 0; i < c.coords.length; i++) {
System.out.println(c.coords[i].x + " " + c.coords[i].y);
}
System.out.println();
}
static void showXYZ(Coords<? super FourD> c) { // super powoduje, ze mozemy uzyc klas w hierarchii w gore - czyli tutaj 3d i 2d.
System.out.println("Wspolrzedne X Y Z: ");
for (int i = 0; i < c.coords.length; i++) {
String a = c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].z;
System.out.println(a);
}
System.out.println();
}
static void showXYZV(Coords<? extends FourD> c) {
System.out.println("Wspolrzedne X Y Z V : ");
for (int i = 0; i < c.coords.length; i++) {
String a = c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].z + " " + c.coords[i].v;
System.out.println(a);
}
System.out.println();
}
public static void main(String args[]) {
TwoD td[] = {
new TwoD(0, 0),
new TwoD(7, 9),
new TwoD(18, 4),
new TwoD(-1, -23)
};
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<TwoD> twoDCoords = new Coords<>(td);
Coords<FourD> fourDCoords = new Coords<>(fd);
System.out.println("Zawartość tdlocs.");
showXY(twoDCoords); // Poprawne, jest typu TwoD.
System.out.println("Zawartość fdlocs.");
// Teraz wszystkie wywołania są poprawne.
showXY(fourDCoords);
showXYZ(fourDCoords);
showXYZV(fourDCoords);
}
}
otóż, chcialbym ograniczyc od dolu metode showXYZ, wiec daje <? super FourD>, co powinno zadziałać, bo FourD rozszerza ThreeD. Jednak kompilator rzuca się, że nie widzi " c.coords[i].z" a powinien, skoro w klasie ThreeD jest:
Error:(16, 79) java: cannot find symbol
symbol: variable z
location: class typysparametryzowane.TwoD
co ciekawe, jak zostanę przy X i Y to już działa, więc wygląda, jakby pomijało całkiem ThreeD.
Proszę o wytłumaczenie, dlaczego 'widzi' mi tutaj TwoD, a nie ThreeD, a jeżeli to idzie do samej góry, to dlaczego TwoD a nie Object.