Static methods 101 in AS3

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.”);

}

}

Advertisements

2 Responses to “Static methods 101 in AS3”

  1. Ktu Says:

    One thing I have noticed, is that if a class extends another that has a static method, the subclass can call the static functions within any other function. A.test() runs both times in B. (hope my html works :] );
    example:

    package utils {
    class A {
    public static function test():void { }
    }
    }

    package utils {
    class B extends A {
    public function A ():void {
    test();
    }
    public static function run():void {
    test();
    }
    }
    }

  2. Matthew Riley Says:

    Thanks. I’ve been reverse engineering a physics engine to help learn ‘the hard stuff’ and was baffled that the subclass had a public static class with the same name as the super. Thus my search which quickly ended here.

    Good things to know.

    M@

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: