Reputation: 317
I found a quite strange problem while making two classes in AS3. Let's call them ParentClass
and ChildClass
. In order to make both of them you need a Sprite
object, then the ParentClass
makes it visible in the stage. ChildClass
inherits the ParentClass
, too.
ParentClass.as:
package myStudio.basic {
import flash.display.MovieClip;
import flash.display.Sprite;
public dynamic class ParentClass extends MovieClip {
public function ParentClass(mc:Sprite=null) {
addChild(mc);
}
}
}
ChildClass.as:
package myStudio.containers {
import myStudio.basic.ParentClass;
import flash.display.MovieClip;
import flash.display.Sprite;
public class ChildClass extends ParentClass {
public function ChildClass(mc:Sprite=null) {
addChild(mc);
}
}
}
Then, I write this code on Frame 1, Layer Actions of the FLA file:
var mc:MovieClip = new childMC;
var vig:ChildClass = new ChildClass(mc);
addChild(vig);
However, I got run-time error #2007:
TypeError: Error #2007: The value of the parameter child must not be null.
at flash.display::DisplayObjectContainer/addChild()
at myStudio.basic::ParentClass()
at myStudio.containers::ChildClass()
at myStudioComicAnimator_fla::MainTimeline/frame1()
I tried overriding the ChildClass
constructor function, but it still doesn't work.
So here's my question: Is there another workaround to solve this problem?
Upvotes: 0
Views: 102
Reputation: 7510
The reason for that is that you are not calling super. You can check what's happening in the error stack (down to top):
The problem is that you cannot add null
as a child. But because the constructor is called internally, there is no param that is being passed to it. so mc
variable is always null
. But as we said - null
cannot be added.
Use the super by yourself:
public function ChildClass(mc:Sprite=null) {
super(mc);
}
This way the ParentClass
will get reference to the mc
object and will be able to add it.
Another option is not to use addChild
in the ParentClass
, but only in ChildClass
. Then it doesn't matter if you pass anything to super, or even if you are calling super at all.
Edit: I forgot to say that this is not a bug, but a standard behavior and works exactly like it should work. The reason for this is that each class can have a whole different override of the constructor. It can take more or less parameters, so the chain for calling parent's constructor is your job to handle.
Upvotes: 2