JAVA 通配符函数问题
JAVA Wildcards Issue with function
这是代码
class TwoD {
int x, y;
public TwoD(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class ThreeD extends TwoD {
int z;
public ThreeD(int x, int y, int z) {
super(x, y);
this.z = z;
}
}
class FourD extends ThreeD {
int t;
public FourD(int x, int y, int z, int t) {
super(x, y, z);
this.t = t;
}
}
class coords<T extends TwoD> {
T cordinates;
public coords(T cordinates) {
super();
this.cordinates = cordinates;
}
static void show(coords<? super ThreeD> c) {}
}
public class mainX {
public static void main(String a[]) {
FourD fourD = new FourD(1, 2,3,4);
coords check = new coords(fourD);
coords.show(check);
TwoD twoD = new TwoD(1, 2);
coords check1 = new coords(twoD);
coords.show(check1);
// How this program runs fine with the child and parent subclass objects in show method?
}
}
方法
静态无效显示(坐标 c)
应该只允许父 class 个对象?为什么它也允许子 class 对象?
该程序如何在 show 方法中与子对象和父对象 subhclass 一起正常运行?
我很困惑!
作为 , you're using raw types 你的 coords
。 (我可以详细说明,但是链接的答案解释得非常清楚。您的用例主要在 原始类型与使用 <?>
作为类型参数有何不同? 和 原始类型是该类型的擦除。)
如果您要更改:
coords check = new coords(fourD);
...
coords check1 = new coords(twoD);
收件人:
coords<FourD> check = new coords<>(fourD);
...
coords<TwoD> check1 = new coords<>(twoD);
您会得到预期的错误:
error: incompatible types: coords<TwoD> cannot be converted to coords<? extends ThreeD>
coords.show(check1);
^
PS/off-topic:Class coords
在遵循 Java 的代码标准时应该使用大写字母 C
(因此 Coords
) .
这是代码
class TwoD {
int x, y;
public TwoD(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class ThreeD extends TwoD {
int z;
public ThreeD(int x, int y, int z) {
super(x, y);
this.z = z;
}
}
class FourD extends ThreeD {
int t;
public FourD(int x, int y, int z, int t) {
super(x, y, z);
this.t = t;
}
}
class coords<T extends TwoD> {
T cordinates;
public coords(T cordinates) {
super();
this.cordinates = cordinates;
}
static void show(coords<? super ThreeD> c) {}
}
public class mainX {
public static void main(String a[]) {
FourD fourD = new FourD(1, 2,3,4);
coords check = new coords(fourD);
coords.show(check);
TwoD twoD = new TwoD(1, 2);
coords check1 = new coords(twoD);
coords.show(check1);
// How this program runs fine with the child and parent subclass objects in show method?
}
}
方法
静态无效显示(坐标 c)
应该只允许父 class 个对象?为什么它也允许子 class 对象? 该程序如何在 show 方法中与子对象和父对象 subhclass 一起正常运行?
我很困惑!
作为 coords
。 (我可以详细说明,但是链接的答案解释得非常清楚。您的用例主要在 原始类型与使用 <?>
作为类型参数有何不同? 和 原始类型是该类型的擦除。)
如果您要更改:
coords check = new coords(fourD);
...
coords check1 = new coords(twoD);
收件人:
coords<FourD> check = new coords<>(fourD);
...
coords<TwoD> check1 = new coords<>(twoD);
您会得到预期的错误:
error: incompatible types: coords<TwoD> cannot be converted to coords<? extends ThreeD>
coords.show(check1);
^
PS/off-topic:Class coords
在遵循 Java 的代码标准时应该使用大写字母 C
(因此 Coords
) .