Turtle Graphics with Java

Bern University of Teacher Education  
HomeStart Online-EditorPrintAndroid-TurtlegraphicsJava-Online

Simple drawing (Sequence)

The simplest programs have of a sequence of actions which are executed in the exact order of appearance. The following example shows a program in which the Turtle draws a square.

Run this example (Tu1.java)

// Tu1.java
import ch.aplu.turtle.*;

class Tu1
{
  Turtle joe = new Turtle();

  Tu1()
  {
    joe.forward(100);
    joe.right(90);
    joe.forward(100);
    joe.right(90);
    joe.forward(100);
    joe.right(90);
    joe.forward(100);
    joe.right(90);
  }

  public static void main(String[] args)
  {
    new Tu1();
  }
}
 

Test this example in the Online-Editor


Explaining the program code:
import ch.aplu.turtle.*;
imports the clas library Turtle
Turtle joe = new Turtle(); generates a new object from the class Turtle
Tu1 ()
{
}
Tu1() is called the constructor of the class Tu1. The constructur always has the same name as the class itself.
joe.forward(100); Turtle joe move forward 100 steps.
joe.right(90); Turtle joe rotates 90 degrees to the right.
public static void main(String[] args) Each Java application needs the method main() which is always defined with the same structure as shown above. The method main() is the first method exectued when running the program. It defines the start of the program.
new Tu1 () ; This generates a new object of the class Tu1. All defined properties and methods from its constructor are executed automatically.

Remarks about the syntax:

Exercises