306 Inheritance
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.
For optimal readability of your code, Macromedia 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.
Overriding methods and properties
When a subclass extends a superclass, the subclass inherits all of the superclass’s methods and
properties. One of the advantages of working with classes and extending classes is that it
allows you not only to provide new functionality to an existing class but also to modify
existing functionality. For example, consider the Widget class that you created in “Example:
Extending the Widget class” on page 304. You could create a new method in your superclass
(Widget) and then either override the method in your subclass (SubWidget) or just use the
inherited method from the Widget class. The following example shows how you can override
existing methods in your classes.
To override methods in a subclass:
1. Create a new ActionScript document and save it as Widget.as.
2. In Widget.as, type the following ActionScript code into the Script window.
Note: If you created the Widget class in an earlier example, modify the existing code by
adding the doSomething() method, as follows:
class Widget {
public static var widgetCount:Number = 0;
public function Widget() {
Widget.widgetCount++;
}
public function doSomething():Void {
trace("Widget::doSomething()");
}
}
CAUTION
If you try to access the static widgetCount variable from the Widget class using the
sw1 or sw2 instances, Flash generates an error telling you that static members can
be accessed only directly through classes.