1
votes

I have some classes that implement an interface, but also extend the Sprite class:

package {
    public interface IState {
        function addMonster():void;
    }
}

package {
    public class Fuzzy extends Sprite implements IState {
        public function addMonster():void {

        }
    }
}

package {
    public class LizardSkin extends Sprite implements IState {
        public function addMonster():void {

        }
    }
}

// Document class 

package {
    public class Main extends MovieClip {
        private var state:IState;
        public function Main():void {
            state = new Fuzzy();

            addChild(state);
        }
    }
}

When I try to addChild(state) I keep getting an error message 1067: Implicit coercion of a value of type IState to an unrelated type flash.display:DisplayObject.

Now I know I've seen examples where a class extends MovieClip / Sprite and implements an interface...what can I do to make it so I can add "state" to the stage but also implement the methods I want??

2

2 Answers

5
votes

A simple cast should do it most of the time:

addChild(state as DisplayObject);

The compiler raises that error otherwise because it doesn't assume IState is always implemented by something that is a DisplayObject, but if you can guarantee that condition you can always cast.

2
votes

What I do in situations like this is use an IDisplayable interface, that looks like this:

public interface IDisplayable
{
   function get displayObject():DisplayObject;
}

and its implementation in a Sprite or MovieClip simply looks like this:

public function get displayObject():DisplayObject
{
     return this;
}

Your IState objects could then be added to the stage using addChild(state.displayObject);, when your IState interface extends IDisplayable.