views:

93

answers:

3

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!

+4  A: 

Java does not support this. You can leverage polymorphism to treat an instance of B as and instance of A but 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 A is in fact an instance of B (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:

Any instance of some type is an instance of some other type.

For instance:

Any instance of Dog is an instance of Mammal.
Any instance of Mammal is an instance of Dog.

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.

Andrew Hare
A: 

Use a copy constructor:

class B extends A{  
    public B(A a){
        this.foo = a.foo;
    }
}
Michael Borgwardt
foo is an int and will not be referenced, it will be copied to a new foo.
Shmoo
There's an easy fix for that - use the `Integer` wrapper class instead of `int`.
Matt Ball
Yes, but editing the A class is not an option in my case.
Shmoo
@Shmoo: it sounds like you basically want to use some feature of class B with a particular instance of class A. Well, you can't do that, period. And I suspect that there's something wrong with your design if you want that.
Michael Borgwardt
A: 

You can't do it plainly because the runtime type of the variable a will be anyway A, not B.

This means that a won't have the characteristics of B.. and you can't obtain it with a cast!

Jack