views:

288

answers:

2

All Objects in actionscript3.0 inherit from the Object class, but the actionscript3.0 compiler seems not to be smart enough to understand this.

take a look at the following code:

package{
   public class TestOne{
      public function TestOne(){
        var t2: TestTwo = new TestTwo();
        trace(t2.toString()); // COMPILE TIME ERROR
        trace((t2 as Object).toString(); // [object TestTwo]

        var t22 : * = new TestTwo();
        trace(t22.toString()); // [object TestTwo]
        trace((t22 as Object).toString(); // [object TestTwo]
      }
   }
}
class TestTwo{}

t2.toString() gives a compile time error because the data type t2 does not include toString(). However, t2 does include toString() because it is an object as (t2 as Object).toString() shows. If we do not give the variable a datatype, like t22, then the problem is never encountered. Why cant the actionscript3.0 compiler relize that t2 is both TestTwo and Object?

+4  A: 

This is because

Methods of the Object class are dynamically created on Object's prototype. To redefine this method in a subclass of Object, do not use the override keyword. For example, a subclass of Object implements function toString():String instead of using an override of the base class.

So if you cast TestTwo to an Object, the compiler knows those methods will be implemented. If you don't cast it, TestTwo does not inherit those methods and so they have not been implemented and will error.

It's a bit of a weird one!

James Hay
Exactly, it is following inheritance to the letter, and toString is not a class method to be inherited, it's on the prototype object.AS3 does follow class inheritance VERY strictly, so if you find a situation where you think it doesn't, chances are that you are missing something, not the compiler!
Bryan Grezeszak
A: 

Class inheritance and prototype inheritance are two different things in AS3. Prototype inheritance is as far as I understand included for backwards compatibility with AS2/AS1, and it's prototype inheritance that's providing the toString() method on the variable that's cast to the Object class in your example. The Object prototype has the toString() method, not the Object class. Since the prototype is not present on your TestTwo class, it doesn't have a toString() method. If the toString() method was supplied via class inheritance instead, your example would compile.

So technically, your statement "All Objects in actionscript3.0 inherit from the Object class" is not entirely correct, because of the difference between prototype inheritance and class inheritance. Prototype inheritance is a somewhat esoteric OO concept found in script languages.

Does anyone know the reason why AS3 is designed like this?

bzlm