Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actionscript 3: Can someone explain to me the concept of static variables and methods?

I'm learning AS3, and am a bit confused as to what a static variable or method does, or how it differs from a method or variable without this keyword. This should be simple enough to answer, I think.

like image 601
Mike Avatar asked Nov 15 '09 18:11

Mike


2 Answers

static specifies that a variable, constant or method belongs to the class instead of the instances of the class. static variable, function or constant can be accessed without creating an instance of the class i.e SomeClass.staticVar. They are not inherited by any subclass and only classes (no interfaces) can have static members.
A static function can not access any non-static members (variables, constants or functions) of the class and you can not use this or super inside a static function. Here is a simple example.

public class SomeClass 
{
  private var s:String;
  public static constant i:Number;
  public static var j:Number = 10;

  public static function getJ():Number 
  {
    return SomeClass.j;
  }
  public static function getSomeString():String 
  {
    return "someString";
  }
}

In the TestStatic, static variables and functions can be accessed without creating an instance of SomeClass.

public class TestStaic 
{
  public function TestStaic():void 
  {
    trace(SomeClass.j);  // prints 10
    trace(SomeClass.getSomeString());  //prints "someString"
    SomeClass.j++; 
    trace(SomeClass.j);  //prints 11
  }
}
like image 163
bhups Avatar answered Sep 19 '22 17:09

bhups


A static variable or method is shared by all instances of a class. That's a pretty decent definition, but may not actually make it as clear as an example...

So in a class Foo maybe you'd want to have a static variable fooCounter to keep track of how many Foo's have been instantiated. (We'll just ignore thread safety for now).

public class Foo {
    private static var fooCounter:int = 0;

    public function Foo() {
        super();
        fooCounter++;
    }

    public static function howManyFoos():int {
        return fooCounter;
    }
}

So each time that you make a new Foo() in the above example, the counter gets incremented. So at any time if we want to know how many Foo's there are, we don't ask an instance for the value of the counter, we ask the Foo class since that information is "static" and applies to the entireFoo class.

var one:Foo = new Foo();
var two:Foo = new Foo();
trace("we have this many Foos: " + Foo.howManyFoos());  // should return 2
like image 37
dustmachine Avatar answered Sep 19 '22 17:09

dustmachine