Overriding a method of a class means redefining a method for a class which would otherwise be inherited. The new method is then used in place of the inherited one (though the inherited method can still be invoked using super).
For ActionScript 3, when you override a method or property of a superclass, you need to use the override attribute with your new method. This specifies that the member you are creating is overriding that which would otherwise be inherited. If you do not use override with a method that already exists in a superclass, an error is thrown at compile time.
Ex:
ActionScript Code:
package {
import flash.display.*;
class MySprite extends Sprite {
private var children:Array = new Array();
public function MySprite() {
}
public override function addChild(child:DisplayObject):DisplayObject {
children.push(child);
super.addChild(child);
return child;
}
}
}
Since addChild exists in the Sprite superclass, the override attribute is needed to successfully define the new addChild method which also adds the child passed to a children array.
Note that the method signature needs to match that of the overriden method
Override works with both normal class methods as well as getter/setter methods (properties), but it will not work with any of the following:
- Variables
- Constants
- Static methods
- Methods that are not inherited
- Methods that implement an interface method
- Inherited methods that are marked as final in the superclass
Also be aware that override is not needed for methods inherited directly from the Object class. These include:
- hasOwnProperty
- isPrototypeOf
- propertyIsEnumerable
- setPropertyIsEnumerable
- toString
- valueOf
These methods are added dynamically and are not part of the actual class definition. The override keyword is to be used only with methods which are part of a class's original definition.
However, if extending a class which uses a method above as part of its defnition, the override keyword is required. For example, if you are extending Object, you do not need to use the override keyword for the toString method. But, if you extend the Sprite class, you will need to override toString since the Sprite class has its own unique toString which is part of its class definition.

0 评论:
发表评论