简体   繁体   English

Java:通用类

[英]Java : generic classes

I read this code from my book: 我从我的书中读取了以下代码:

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

Why B b = gb.e; 为什么B b = gb.e; arise an error? 出现错误? We didn't assign anything to b, and for that gb.e is from type B. 我们没有为b分配任何东西,因为gb.e来自B类型。

With your exact setup, I've obtained an error from the compiler (Sun Java Compiler version 1.6.x) at the line where you attempt to create the second reference to the instance of the object G: 使用您的准确设置,在尝试创建对对象G实例的第二个引用的行中,我从编译器(Sun Java Compiler版本1.6.x)获得了一个错误:

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

Attempting to swap where the conversion happens also fails: 尝试在发生转换的位置进行交换也将失败:

Code: 码:

G<A> ga = new G<A>();
G<B> gb = ga;
gb.e = new A();
B b = gb.e;

Error: 错误:

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

Are you positive this isn't an issue with the prior lines? 您是否肯定这与先前的版本无关? I'm not having luck with this case. 我没有这种情况的运气。

Even if the case is that you managed to make it that far, this should still fail because of not knowing the proper type of when trying to get a new B reference. 即使情况是您设法做到了这一点,也应该会失败,因为在尝试获取新的B引用时不知道正确的类型。 Since you can only convert upward (so, A instance = new B() would be OK. B instance = new A() would not be) it wouldn't makes sense to take the instance of A and move it down the hierarchy to a type of B. 由于您只能向上转换(因此, A instance = new B()可以, B instance = new A()可以),因此将A的实例向下移动到层次结构中没有任何意义。 B型

you are attempting to cast a class to one of its subclasses and not the other way around. 您正在尝试将一个类强制转换为其子类之一,而不是相反。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM