Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:泛型类_Java - Fatal编程技术网

Java:泛型类

Java:泛型类,java,Java,我从书中读到了以下代码: class B extends A {...} class G<E> { public E e; } G<B> gb = new G<B>(); G<A> ga = gb; ga.e = new A(); B b = gb.e; // Error 类B扩展了{…} G类{ 公共教育; } G gb=新的G(); G ga=gb; ga.e=新的A(); B=gb.e;//错误 为什么bb=gb.e是否出现错误?我们没有

我从书中读到了以下代码:

class B extends A {...}
class G<E> {
public E e;
}
G<B> gb = new G<B>();
G<A> ga = gb;
ga.e = new A();
B b = gb.e; // Error
类B扩展了{…} G类{ 公共教育; } G gb=新的G(); G ga=gb; ga.e=新的A(); B=gb.e;//错误
为什么
bb=gb.e是否出现错误?我们没有给b赋值,因为gb.e来自类型b。

您试图将一个类强制转换为它的一个子类,而不是相反

A a;
B b;

a = new B(); // works because B is a subclass of A
b = new A(); // fails because A is a superclass of B

通过您的精确设置,我从编译器(Sun Java compiler version 1.6.x)获取了一个错误,在您尝试创建对对象G实例的第二个引用的行中:

G.java:6: incompatible types
found   : G<B>
required: G<A>
                G<A> ga = gb;
                          ^
1 error
G.java:6:不兼容类型
发现:G
所需:G
G ga=gb;
^
1错误
在发生转换的地方尝试交换也会失败:

代码:

G ga=new G();
G gb=ga;
gb.e=新的A();
B=gb.e;
错误:

G.java:6: inconvertible types
found   : G<A>
required: G<B>
                G<B> gb = (G<B>)ga;
                                ^
G.java:7: incompatible types
found   : A
required: B
                gb.e = new A();
                       ^
2 errors
G.java:6:不可转换类型
发现:G
所需:G
G gb=(G)ga;
^
G.java:7:不兼容的类型
发现:A
所需:B
gb.e=新的A();
^
2个错误
你确定这不是先前的线路的问题吗?我在这个案子上运气不好


即使您成功地做到了这一点,这仍然会失败,因为在尝试获取新的B引用时不知道正确的类型。由于您只能向上转换(因此,
A instance=new B()
就可以了。
B instance=new A()
就不可以了),所以将A的实例在层次结构中向下移动到B的类型是没有意义的。

但是为什么gb来自类型A?这是一行:“ga.e=newa();”为gb和ga定义它们来自类型A?您确定错误只发生在
B B=gb.e的行中吗?而不是之前,in
G ga=gb?@Vineet Reynolds:不。因为我害怕,那根本不是。请随意张贴代码,在同一行中复制相同的错误。在我看来,Eclipse编译器javac和ideone的代码行
gga=gb应该给出一个错误,因为使用了严格的类型检查。
G.java:6: inconvertible types
found   : G<A>
required: G<B>
                G<B> gb = (G<B>)ga;
                                ^
G.java:7: incompatible types
found   : A
required: B
                gb.e = new A();
                       ^
2 errors