LAB 35 – Creating Classes (part 4 – extending turtles)
Lab Exercises
Topics
n To extend classes.
n To introduce dynamic binding
Exercises
11.9 Reusing a Class via Inheritance
i) Open a new file in Dr. Java and type in the following enumerated data type:
public class ConfusedTurtle extends Turtle
{
}
ii) Add the following code to the class:
/**
* Constructor that takes a world and calls the parent constructor
* @param theWorld the world to put the confused turtle in
*/
public ConfusedTurtle(World theWorld)
{
super (theWorld);
}
iii) Add the following code to the class:
/**
* Method to turn left (but confused turtles turn right)
*/
public void turnLeft()
{
super.turnRight();
}
/**
* Method to turn right (but confused turtles turn left)
*/
public void turnRight()
{
super.turnLeft();
}
iv) create a Turtle and ConfusedTurtle and test them:
> World earth = new World();
> Turtle tommy = new Turtle(earth);
> tommy.forward();
> tommy.turnLeft();
> ConfusedTurtle bruce = new ConfusedTurtle(earth);
> bruce.backward();
> bruce.turnLeft();
> bruce.forward();
> tommy.forward();
> tommy.turnRight();
> bruce.turnRight();
v) Note that you could have also declared a Turtle and then created it as a ConfusedTurtle by
Turtle alice = new ConfusedTurtle(earth);
vi) Add other methods to ConfusedTurtle for forward, backward, and turn.
vii) Create a DrunkenTurtle class using a random number for the angle and distance for turnRight, turnLeft, turn, forward, and backward.
QUESTIONS:
Nothing to Submit.