views:

626

answers:

2

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.

+1  A: 

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.

Alex Jillard
A: 

An addition to Alex Jillard's answer: it's possible to cast a variable of type A to type B if the value in instanceofA is already of type B.

So if you have

var instanceOfA:A = new B();

then this will work:

instanceOfB = instanceOfA as B;

This comes up when handling events. The currentTarget property on MouseEvent is declared as type Object, but at runtime it's likely to be a Sprite or MovieClip.

Selene