Static methods 101 in AS3

By maohao

Static methods cannot be overridden in subclasses (doesn’t allow for polymorphism) since they are resolved at compile time.

Each class can define their own static methods with the same name/signature of the static methods as defined in their subclasses/superclasses. Same thing for static variables. You cannot use “override” in such a situation since static methods and variables don’t exist within the inheritance chain of the class in AS3 while polymorphism is determined by AVM at run-time.

It is permissible to define an instance property/method using the same name as a static property/method since instance properties/methods are resolved at run-time. (Note that if the static variable has an accessors method which has the same name as a variable, your code won’t work properly.)

The following code will compile:

class A
{
public var NAME:String = "A";

public static var NAME:String= "A Static";

public function name():String
{
return this.NAME;
}


public static function name():String
{
return A.NAME;
}


protected function walk():void

{

trace(”an A is walking.”);

}

}

Class B extends A

{

//Cannot say “override static function walk()” since we are NOT overriding an instance method.

public static function walk():void

{

trace(”Everyone who is B is walking.”);

}

}

Leave a Reply