Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Inheritance > About writing subclasses in Flash > About writing a subclass > Example: Extending the Widget class | |||
Class members propagate to subclasses of the superclass that defines those members. The next example demonstrates how you could create a Widget class, which you extend (subclass) by writing a class named SubWidget.
class Widget {
public static var widgetCount:Number = 0;
public function Widget() {
Widget.widgetCount++;
}
}
class SubWidget extends Widget {
public function SubWidget() {
trace("Creating subwidget #" + Widget.widgetCount);
}
}
var sw1:SubWidget = new SubWidget();
var sw2:SubWidget = new SubWidget();
trace("Widget.widgetCount = " + Widget.widgetCount);
trace("SubWidget.widgetCount = " + SubWidget.widgetCount);
The previous code creates two instances of the SubWidget class: sw1 and sw2. Each call to the SubWidget constructor traces the current value of the static Widget.widgetCount property. Because the SubWidget class is a subclass of the Widget class, you can access the widgetCount property through the SubWidget class, and the compiler rewrites the reference (in the bytecode, not in your ActionScript file) as Widget.widgetCount. If you try to access the static widgetCount property off of instances of the Widget or SubWidget class, like sw1 or sw2, the compiler throws an error.
The Output panel displays the following output:
Creating subwidget #1 Creating subwidget #2 Widget.widgetCount = 2 SubWidget.widgetCount = 2
You see this output because even though the Widget class's constructor is never explicitly called, the SubWidget class's constructor calls it for you. This causes the Widget class's constructor to increment the Widget class's static widgetCount variable.
The ActionScript 2.0 compiler can resolve static member references within class definitions.
If you don't specify the class name for the Widget.widgetCount property but instead refer only to widgetCount, the ActionScript 2.0 compiler resolves the reference to Widget.widgetCount and correctly exports that property. Similarly, if you refer to the property as SubWidget.widgetCount, the compiler rewrites the reference (in the bytecode, not in your ActionScript file) as Widget.widgetCount because SubWidget is a subclass of the Widget class.
|
CAUTION |
|
If you try to access the static |
For optimal readability of your code, Adobe recommends that you always use explicit references to static member variables in your code, as shown in the previous example. Using explicit references means that you can easily identify where the definition of a static member resides.
Flash CS3