Some notes on inheritance in ActionScript 2

When implementing super and subclasses, Flash will call the superclass’ constructor automatically unless you call it yourself.
Imagine you have the following code:

class Super { 
   public function Super () {
       trace ("super called");
   }
}

class Sub extends Super { 
}

var myObject:Object = new Sub();

Result? Yes indeed, it traces “super called”. The constructor for Sub doesn’t exist, so the default constructor is used, which calls the super class constructor by default.
All’s fine…

Next example:

class Super { 
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }
}

class Sub extends Super { 
}

var myObject:Object = new Sub();

Result? The super constructor is still called! (To my amazement, but anyway). It is called with no parameters since we didn’t pass any, so I guess that was to be expected. So although this is a little evidence that we should have called the constructor explicitly, it still wouldn’t have prevented us from calling it without parameters.

Ok, next bit of code:

class Super { 
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }

   public function mySuperMethod() {
   }
}

class Sub extends Super { 
    public function Sub() {
    }
}

var myObject:Object = new Sub();

Result? Yes, the super constructor is still called, since that was the default behavior. Us defining a constructor doesn’t mean we have overridden the superclass constructor.

Ok, let’s move on!

class Super { 
   public function Super (pName:String) {
       trace ("super called with "+pName);
   }

   public function mySuperMethod() {
   }
}

class Sub extends Super { 
    public function Sub() {
        super.mySuperMethod();
    }
}

var myObject:Object = new Sub();

Result? The super constructor is NO LONGER called. Appearently something is getting messed up by the super. statement. In both the Flash IDE and the MTASC compiler the super constructor fails to run. If we replace super.mySuperMethod(); with mySuperMethod(); the super constructor is called again. Note that super.mySuperMethod is NOT a case of calling the superclass’ constructor, I’m simply calling one of the superclass’ methods.

Conclusions:

  • always called super ( … ) ; explicitly
  • do not use super. to clarify your code, unless you consequently follow the first rule
image_pdfimage_print
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *