96 methods

AS3 Class Constructor Overloading

I discovered yesterday that it’s not possible to implement constructor overloading in ActionScript 3.

Take the following code sample for example. This will give a compilation error because more than one constructor is defined:

public class MyClass {

private var _dataMember:int;
public function MyClass() {
_dataMember = 0;
}
public function MyClass(value:int) {
_dataMember = value;
}
}

To get around this limitation we can define a single constructor but give the parameters of the constructor default values, thus:

public class MyClass {

private var _dataMember:int;

public function MyClass(value:int = 0) {
_dataMember = value;
}
}

Now we can either pass an initial value to the constructor when we declare a new instance of MyClass or pass nothing and have the default value used:

// _dataMember will default to 0:

var example1:MyClass = new MyClass();
// _dataMember will be set to -1:
var example2:MyClass = new MyClass(-1);

More information can be found at:
http://workingwithmrb.blogspot.com/2008/09/darren-on-flex-overloading-constructor.html

Posted by Graham Blake on 26th March 2009 at 09:02

Comments

Write a Comment

Categories

Feedback

Drop me an email.