I have the following classes in ActionScript:
public class A {
}
public class B extends A {
}
and these variables (in another class):
public var InstanceOfA:A;
public var InstanceOfB:B;
How do I cast an instance of A as a class B?
I tried:
InstanceOfA = new A();
InstanceOfB = InstanceOfA as B;
trace(InstanceOfB);
I get an object of type A for InstanceOfB.
I also tried:
instanceOfB = B(InstanceOfA);
In this case, I get a 'Type Coercion Failed' error.
With casting you can only cast from more to less specific. Since B extends A, it would, in theory, contain more specific code that class A would not contain. Because of this, it is possible to cast B as A (since B is an A), but you couldn't cast A as B because A isn't a B.
To put that in a probably more logical way, say class A is "Animal" and class B is "Dog". Dog is a more specific implementation of an Animal.
Dog is an Animal, so you can cast Dog as an Animal, but you can't take an Animal and cast it as a Dog, because not every Animal is a Dog.
Hope that makes sense.
Now, if you wanted to do something like you have above, you could either have both A and B extend an Abstract base class, or implement an Interface and type both of your instance variables as either the abstract class or the interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With