Inheritance • The following tasks is about a turtle and the world in which it li
ID: 3769676 • Letter: I
Question
Inheritance
• The following tasks is about a turtle and the world in which it lives. One can
ask the turtle to move around in the world by calling specific methods. The
turtle has a pen attached to its underside and therefor it leaves a track when
it moves around (if the pen in down of course). This is illustrated in the
following snippet of code. (World- and SimpleTurtle classes are a part of the
imvapi):
World w = new World(800, 800);
SimpleTurtle t = new SimpleTurtle(w);
t.forward(100);
t.turnRight();
t.forward(100);
t.turnRight();
Start by examining which methods the SimpleTurtle contain.
1. Expand the SimpleTurtle class So that we can add new methods to it
(inheritance). For example you may name the new class Turtle. Make
sure that the above snippet still works with the new class by invoking the
super class constructor:
public Turtle(ModelDisplay display) {
super(display);
}
2. Write a method enabling the new turtle to draw a square of arbitrary
size on a given position (x,y).
3. Write a method enabling the new turtle to draw a shape of n (arbitrary
number) sides.
4. Write a method enabling the new turtle to draw a five-pointed star
5. Write a method enabling the new turtle to draw a n-pointed star
6. Write a method enabling the new turtle to draw a house.
HINT: You may want to create several methods that each draw an element of the house and call
these in the right order.
Explanation / Answer
The following program is as per your query.
import java.awt.*;
import com.otherwise.jurtle.*;
public class FancyBox extends Turtle
{
public void runTurtle()
{
setPenWidth(10);
setAutoUpdatePause(400);
setPenColor(Color.green);
forward(100);
right(90);
setPenColor(Color.red);
forward(100);
right(90);
setPenColor(Color.blue);
forward(100);
right(90);
setPenColor(Color.yellow);
forward(100);
right(90);
hideTurtle();
}
}
This is the second.
import java.awt.*;
import com.otherwise.jurtle.*;
public class BorderBox extends Turtle
{
public void runTurtle()
{
// Do some setup.
setAutoUpdatePause( 200 );
setPenWidth( 20 );
setPenColor( Color.orange );
// Get the display's size.
Dimension size = getDisplaySize();
// Position the turtle in the upper left
penUp();
setPosition( 20, 20 );
penDown();
// Now move to the four corners with the pen down.
setPosition( size.width - 10, 10 );
setPosition( size.width - 10, size.height - 10 );
setPosition( 10, size.height - 10 );
setPosition( 10, 10);
hideTurtle();
}
}