
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
170
|
Chapter 6: Inheritance
Invoking an Overridden Instance Method
When a subclass overrides an instance method, the superclass’s version of the
method is not lost. It remains accessible to instances of the subclass via the super
operator, which can invoke an overridden method as follows:
super.methodName(arg1, arg2, ...argn);
where methodName is the name of the overridden method to invoke, and arg1, arg2,
...
argn are the arguments to pass to that method. (We’ll learn more about other
uses of super later in this chapter.)
Let’s see how to use super to invoke a method of the superclass that is overridden. So
far, our Square.setSize( ) method needlessly duplicates the code in the Rectangle.
setSize( ) method. The Rectangle version is:
public function setSize (newW:Number, newH:Number):Void {
w = newW;
h = newH;
}
The Square version of setSize( ) merely adds an if statement:
public function setSize (newW:Number, newH:Number):Void {
if (newW == newH) {
w = newW;
h = newH;
}
}
To avoid the duplication of setting w and h in both methods, we can use super,as
shown in this revised version of Square.setSize( ):
public function setSize (newW:Number, newH:Number):Void {
if (newW == newH) {
// Invoke the superclass's setSize( ) method, in this case
// Rectangle.setSize( ), on the current instance.