Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

Use a copy constructor:

class B extends A{  
    public B(A a){
        this.foo = a.foo;
    }
}

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top