|
From: Kevin B. <kb...@ca...> - 2001-06-29 23:11:32
|
Woops!
I completely misread your post:
Marco wrote:
> how can i cast a java-instance to another type.
> ex.
> x = myJavaClass1()
> y = (myJavaClass2) x
>
> where:
> myJavaClass2 extends myJavaClass1
So you have:
public class A
{
}
public class B extends A
{
}
and you want to do:
{
A a = new A();
B b = (B) a;
}
Right?
You can't do that -- you will get a ClassCastException, because you're trying to use an object as if it were something it _knows_ it is not.
You can only cast to what the instance _really_ _is_.
The usual pattern is:
{
A a = new B();
B b = (B) b;
}
Which works as I described: So I've been using an instance of B as if it were an instance of A, but after the cast, I want to use it as what it really is.
The idiom, if you _really_ have an "A" and need to get a "B" is to do do a shallow copy/a delegation pattern something like this:
public B( A other ) // "copy constructor"
{
// either a shallow copy, as you said, or retain reference to 'other' instance to delegate to
}
public static B makeB( A other )
{
if ( other instanceof B )
{
return (B) other;
}
else
{
return new B( other );
}
}
This is not something you want to do often, and generally indicates you have a problem in the design.
kb
|