Why would I be unable to convert an instance of a class to an instance of the class's subclass in AS3?
I'm using a library that has a function that returns an instance of some class Engin开发者_Python百科e
.
I'd like to tack on some interfaces to Engine
, so I subclass it class InterfacedEngine extends Engine implements AwesomeInterface
.
But when I change the code that uses the classes from this:
var engine:Engine = generateEngine();
to this:
var interfacedEngine:InterfacedEngine = generateEngine();
It gives me a runtime error (elision mine):
TypeError: Error #1034: Type Coercion failed: cannot convert ...::Engine@1bc2bf11 to ....InterfacedEngine.
What about AS3 classes am I misunderstanding?
One solution to this kind of problem is the Proxy design pattern. You can read up on it here: http://www.oodesign.com/proxy-pattern.html
Basically you create a placeholder for another class. This is done through composition instead of inheritance though.
InterfaceEngine should accept an object of type Engine as a constructor parameter. AwesomeINterface defines all the Engine methods you need. InterfaceEngine just passes the method call to the corresponding meths of the Engine object it's holding onto.
If B is the base class and D extends B then a D is a B, but not the opposite. That means a reference of type B can refer to both B and D. But a reference of type D can only refer to D, not B. InterfacedEngine
can only refer InterfacedEngine
, not it's base Engine
. But a Engine
type can refer to both Engine
and InterfacedEngine
.
var eng1:Engine = new Engine(); // valid
var eng2:Engine = new InterfacedEngine(); // valid
var eng3:InterfacedEngine = new InterfacedEngine(); // valid
var eng4:InterfacedEngine = new Engine(); // not valid
精彩评论