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 from 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:
Attempting to swap where the conversion happens also fails:
Code:
Error:
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.