
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Overriding Methods and Properties
|
171
public function setSize (newW:Number, newH:Number):Void {
// Call Rectangle.setSize( ).
super.setSize(newW, newH);
// Now render the rectangle on screen.
draw( );
}
public function draw ( ):Void {
// Screen-rendering code goes here.
// For example rendering code, see Example 4-6.
}
}
Finally, overriding can be used to nullify the behavior of a method. The technique is
straightforward: the subclass’s version of the overridden method simply does noth-
ing. For example, the following code shows a subclass named ReadOnlyRectangle that
disables the Rectangle.setSize( ) method, preventing an instance from changing size:
class ReadOnlyRectangle extends Rectangle {
// This effectively disables the setSize( ) method
// for instances of the ReadOnlyRectangle class.
public function setSize (newW:Number, newH:Number):Void {
// Do nothing.
}
}
Nullifying a method is legal but, in most cases, not considered good OOP practice.
Generally speaking, every subclass should support the methods of its superclass(es).
That way, external code can safely use the superclass’s methods on instances of the
subclass (as we’ll see later, treating unlike objects alike is an important part of
polymorphism).
Overriding Class Methods
We saw earlier how to override instance methods ...