AS2 OOP: Inheritance
         by senocular

Super
In ActionScript 1.0, the super command was used to gain access the super class directly, most commonly to call the super class constructor to initialize the subclass, though it gave access to both the constructor as well as methods. Good news! Super is still here with ActionScript 2.0. Better news! If you don't include the super() call in your subclass's constructor function (much in the way of the constructor itself). Flash will add it for you!

One new restriction included with super's use in ActionScript 2.0 is that when using it to call the super class constructor in a sub class, you'll need to be sure you call it as the very first thing in the subclass's constructor. Otherwise, the compiler will complain and give you an error. This isn't necessarily a bad thing though. This is where super is supposed to be called. So it's good the compiler lets you know when you've faltered in doing otherwise. This is also where its called if you don't include it yourself. Calling it yourself, though, allows you to pass arguments into the super class call. When its called automatically, its run without any arguments passed.

Example.

// in Furniture.as
class Furniture {
var material:String;
function Furniture(madeOf:String) {
material = madeOf;
}
function describe():Void {
trace("Made of fine quality "+ material +".");
}
}
// in Chair.as
class Chair extends Furniture {
var legs:Number;
function Chair(madeOf:String, legCount:Number) {
super(madeOf);
legs = legCount;
}
function describe():Void {
trace("Complete with "+ legs +" legs.");
super.describe();
}
}
// in Flash movie
var item:Chair = new Chair("Mahogany", 4);
item.describe();
 
/* output:
Complete with 4 legs.
Made of fine quality Mahogany.
*/

Try it yourself! (zipped source)

Chair is a sub class of Furniture. Super is used to pass arguments to the Furniture constructor when called and to access a similarly named method within one of its own - just like in ActionScript 1.0.

 




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.