Jojit Soriano's Blog

July 1, 2009

Flex Workaround: ActionScript Does Not Support Method Overloading

Filed under: Uncategorized — jojitsoriano @ 8:43 am
Tags: ,

C#, VB.Net, and Java support method overloading, i.e. one can define two methods of the same name but with different parameters. For example, you can have a method named ShowName with a string parameter named pstrFirstName and you can have another method with the same name but with two string parameters named pstrFirstName and pstrLastName. This is method overloading and this is available also to class constructors. A class may be defined with multiple constructors. For example, you can have a default constructor, i.e. no parameters, and you can have two other constructors but with varying number of parameters depending on your requirement.

Unfortunately, ActionScript does not support method overloading! You cannot have two methods or two constructors having the same name even though they have different sets of parameters. The good news is that ActionScript provides …(rest) parameter to allow the developer to define a method that can accept any number of parameters. For example, if you want to create a single method that can add two, three, four, or more numbers, you can use the …(rest) parameter. This parameter declaration must be the last parameter specified.

The following code snippet shows a constructor for a class named AppBase that inherits from Canvas. My goal for this constructor with …(rest) parameter is to be able to use this class as a control in an MXML but at the same time to be able to instantiate the class with certain parameters. When you create a control and you want that control to be declared in MXML, the constructor of the control must have no parameter. In this snippet, I named the …(rest) parameter as …p_Args and is an array from which you can obtain the elements by specifying its index.

private var mstrAppId : String;
private var mstrJSessionId : String;
private var mstrServerUrl : String;
private var mstrWsdl : String;
public function AppBase(…p_Args)
{
    super();
    if(p_Args.length == 4)
    {
         mstrAppId = p_Args[0];
         mstrServerUrl = p_Args[1];
         mstrJSessionId = p_Args[2];
         mstrWsdl = p_Args[3];
    }
}

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.