I got the following:
class A{
int foo;
}
class B extends A{
public void bar();
}
I got a instance of A and want to convert it to an instance of B without losing the reference to the variable foo.
For example:
A a = new A();
a.foo = 2;
B b = a; <-- what I want to do.
//use b
b.foo = 3;
//a.foo should now be 3
Thanks for any help!
Java does not support this. You can leverage polymorphism to treat an instance of
Bas and instance ofAbut not the other way around.The reason you cannot do this is because there is no type-safe way to guarantee that your instance of
Ais in fact an instance ofB(you could cast the instance but even if you did you would only be guaranteeing yourself an exception at execution time).The best way to tell if there is a type-safe, polymorphic relationship between types is to test this statement for validity:
For instance:
Notice that the first example is true while the second is false. What you are trying to do in your code example is exactly like trying to treat any mammal as a dog – even though it may be true occasionally it is not true categorically which means the compiler will not allow it.
Again, for times when it could be true you must cast the reference but this opens you up for exceptions at execution time. Your specific example above is one of those times when an exception would occur as we can clearly see that you have instantiated an instance of type
A.