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;
arise an error? We didn't assign anything to b, and for that gb.e is f开发者_运维百科rom type 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.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. 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.
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
精彩评论