Overriding |
Last time we added falling tomatoes to our collection of falling objects. We achieved this by overriding the run method from FallingObject with a tomato-specific version in Tomato.
The code super.run() in that method tells Java to execute the run method of the superclass, FallingObject. This drops the object and removes it from the canvas. Then we create a new FilledOval to represent the tomato getting squished.
This works, but you might wonder if other things that could fall from clouds might also have some special behavior when they're done falling. Perhaps in some cases, we don't want the object that was falling to be removed from the canvas at all (maybe we want our leaves and sleet to accumumulate).
We can modify our FallingObject class to allow for these possibilities, while still retaining its original functionality.
public class FallingObject extends ActiveObject { ... // The run method public void run() { while (object.getY() < fallToPos) { pause(DELAY_TIME); object.move(0, ySpeed); } hitBottom(); } // default "hit bottom" behavior - may be overridden protected void hitBottom() { object.removeFromCanvas(); }
Now our tomato can override only the hitBottom method.
Demo: FallingObjectsWithCows
Which of our solutions for specifying the "hit bottom" behavior, or
other "enhanced" behaviors, is better? It depends. In many cases,
either approach will work, but one or the other results in clearer or
less complex code.
Overriding |