Overriding |
Let's create another extension of our FallingObject. This is a weird storm and in addition to leaves and sleet, tomatoes are falling from the sky. Adding these tomatoes (red ovals) as a third option isn't too hard - we just extend FallingObject once again and this time draw red ovals in the constructor. We also modify the Tree to create leaves, sleet, or tomatoes.
Demo: Falling leaves with TomatoesBalloons
But tomatoes don't just disappear when they hit the ground. While we could reasonably imagine leaves and sleet decomposing or melting when it hits the ground, we might want to make our tomatoes splat when they reach the ground.
The important difference here is that after the usual falling, done by the run method of FallingObject, we want to show the tomato splay. Here, we only replace the circle by an elongated oval.
We achieve this by overriding the run method from FallingObject with a tomato-specific version in Tomato. See the on-line code.
The code super.run() 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: FallingObjectsWithCowsother "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 |