Wednesday, May 19, 2010

Constructor execution order in Actionscript 3.0

While working on one of my project, I came across off the track behavior of flash player while executing class constructor. It was observed that flash player while compiling class checks whether the class constructor has explicit call to its super class constructor [anywhere from its constructor], if true flash player does not implicitly calls super class constructor else first statement to be executed in class is call to super class constructor.

To explain above statement, let’s take an example, Base class is the parent class for Child class and their structure is as follows

package
{
   public class Base
   {
      protected var baseClassProperty:String;
      public function Base()
      {
         trace("Base Constructor is called");
         baseClassProperty = "Hello World from Base class";
      }
   }
}


package
{
   public class Child extends Base
   {
     public function Child()
      {
        trace("Child Constructor is called");
      }
   }
}

Now if we instantiate Child class as

var childObj:Child = new Child();

When above statement is executed, following will be the output

Base Constructor is called
Child Constructor is called

As expected Flash player will implicitly add call to super class constructor as first statement and hence we will have base class trace first statement and child class trace as second statement in output panel.

In case if Child class implicitly add call to super class constructor

package
{
   public class Base
   {
      protected var baseClassProperty:String;
      public function Base()
      {
         trace("Base Constructor is called");
         baseClassProperty = "Hello World from Base class";
      }
   }
}


package
{
   public class Child extends Base
   {
      public function Child()
      {
         trace("Child Constructor is called");
         super();
      }
   }
}

Now if we instantiate Child class, following statement will be displayed in out panel.

Child Constructor is called
Base Constructor is called

As we have explicitly called super class constructor form Child class, Flash player will not implicitly add call to super class constructor as first statement and hence we will have child class trace as a first statement and base class trace as a second statement in output panel.


Accessing Base class variable from Child class.

While accessing Base class variable from Child class, where Base class is parent class of Child class, it is advisable to accessing variable only after explicit call to Base class constructor in Child class when Child class has explicit call to Base class constructor or can be access at any level if call to Base class constructor is implicit in Child class. In cases when Base class variable if access before implicitly/explicit call to Base class constructor may many time give unexpected result.

No comments:

Post a Comment