Macromedia flex 2 Manuale
Adding properties and methods to a component
137
Defining a method override
You can override a method of a base class in your ActionScript component. To override the
method, you add a method with the same signature to your class, and prefix it with the
method, you add a method with the same signature to your class, and prefix it with the
override
keyword. The following example overrides the
HBox.addChild()
method to open
an Alert box when a new item is added to it:
package myComponents
{
import mx.controls.Alert;
import mx.containers.HBox;
import flash.display.DisplayObject;
{
import mx.controls.Alert;
import mx.containers.HBox;
import flash.display.DisplayObject;
public class HBoxWithAlert extends HBox
{
// Define the constructor.
public function HBoxWithAlert()
{
super();
}
{
// Define the constructor.
public function HBoxWithAlert()
{
super();
}
// Define the override.
override public function addChild(child:DisplayObject):DisplayObject {
// Call super.addChild().
super.addChild(child);
// Open the Alert box.
Alert.show("Item added successfully");
override public function addChild(child:DisplayObject):DisplayObject {
// Call super.addChild().
super.addChild(child);
// Open the Alert box.
Alert.show("Item added successfully");
return child;
}
}
}
}
}
}
Notice that the method implementation calls the
super.addChild()
method. The call to
super.addChild()
causes Flex to invoke the superclass’s
addChild()
method to perform the
operation. Your new functionality to open the Alert box occurs after the
super.addChild()
method.
You might have to use
super()
to call the base class method before your code, after your
code, or not at all. The location is determined by your requirements. To add functionality to
the method, you call
the method, you call
super()
before your code. To replace the base class method, you do not
call
super()
at all.