![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
One use of class (static) members is to maintain state information about a class and its instances. For example, suppose you want to keep track of the number of instances that have been created from a particular class. An easy way to do this is to use a class property that's incremented each time a new instance is created.
In the following example, you'll create a class called Widget that defines a single, static instance counter named widgetCount
. Each time a new instance of the class is created, the value of widgetCount
is incremented by 1 and the current value of widgetCount
is displayed in the Output panel.
class Widget { static var widgetCount:Number = 0; // initialize class variable function Widget() { trace("Creating widget #" + widgetCount); widgetCount++; } }
The widgetCount
variable is declared as static, and so initializes to 0 only once. Each time the Widget class's constructor function is called, it adds 1 to widgetCount
, and then displays the number of the current instance that's being created.
In this file, you'll create new instances of the Widget class.
// Before you create any instances of the class, // widgetCount is zero (0) trace("Widget count at start: " + Widget.widgetCount); var widget_1 = new Widget(); var widget_2 = new Widget(); var widget_3 = new Widget();
You should see the following in the Output panel:
Widget count at start: 0 Creating widget # 0 Creating widget # 1 Creating widget # 2
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |