Skip to main content
July 20, 2010
Question

OOP, constructors. Why is the object null?

  • July 20, 2010
  • 1 reply
  • 442 views

Hi. Here's AS3 behavior that I don't quite understand. The code is:

public class TestA
{
      public var data:Object;

      public function TestA()
      {
           trace("From A", this.data);
     }

}

public class TestB extends TestA
{

     public function TestB()
     {
         //this.data = { test: 5 };
         this.data = new Object();
         trace("From B", this.data);
         super();
     }

}

import flash.display.Sprite;

public class TestApp extends Sprite
{
      public function TestApp()
      {
          var t:TestB = new TestB();
      }

}

This outputs

From B [object Object]
From A null

where I would expect

From B [object Object]
From A [object Object]

How come?

Using Flex 4 SDK with FlashDevelop.

This topic has been closed for replies.

1 reply

Inspiring
July 20, 2010

Because by calling super() constructor you nullify the object.

Try this:

package
{
     public class TestA
     {
          public var data:Object;

          public function TestA()
          {
               trace("From A", this.data);
               getData();
          }
          
          public function getData():void
          {
               trace("From A", this.data);
          }

     }

}

package
{
     public class TestB extends TestA
     {
          public function TestB()
          {
               data = new Object();
               trace("From B constructor", this.data);
               getData();
               thisData();
               super();
               getData();
               thisData();
          }
          
          private function thisData():void {
               trace("From B thisData", this.data);
          }

     }
}

July 20, 2010

OK, I took your point and tried the same in Java language. And Java compiler gave me an error:

Call to super must be first statement in constructor.

It seems that ActionScript compiler is missing this sort of compile-time error or warning at least, because what we have is an access to undefined data (as I understood, default values are set in the super() constructor call). For example, if we substitute data:Object with data:Number, we will get that data equals 0, not NaN (before calling super constructor). Where did that 0 value come from and won't we get a piece of another process' memory next time?

Inspiring
July 20, 2010

In AS you can call super at any point in the constructor - so it is not an incorrect syntax. super() is called automatically if there is no explicit call.

As for the 0 vs NaN - feels like bug but I am not sure. Looks like it is set to default 0 but after constructor is called - it resets to NaN. I couldn't replicate it in any other situations of Number declaration. Interesting...