Java:泛型类

时间:2011-06-18 19:59:54

标签: 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 b = gb.e;出现错误?我们没有给b指定任何东西,因为gb.e来自B类。

2 个答案:

答案 0 :(得分:1)

使用您的确切设置,我在编译器(Sun Java编译器版本1.6.x)的行中尝试创建对象G实例的第二个引用时收到错误:

G.java:6: incompatible types
found   : G<B>
required: G<A>
                G<A> ga = gb;
                          ^
1 error

尝试交换转换发生的位置也会失败:

代码:

G<A> ga = new G<A>();
G<B> gb = ga;
gb.e = new A();
B 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

你是肯定的,这不是前几行的问题吗?我对这个案子没有好运。

即使案例是你设法做到这一点,这仍然会失败,因为在尝试获取新的B引用时不知道正确的类型。因为你只能向上转换(所以,A instance = new B()就行了。B instance = new A()不会是这样的。拿A的实例并将它从层次结构向下移动到B的类型是没有意义的

答案 1 :(得分:0)

你试图将一个类强制转换为其子类之一,而不是相反。

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
相关问题