CS1026 Computer Science Fundamentals I (Java)

Lab 4: Getters and Setters


Objectives
Preparation

Exercise 0: Setting up the media sources


Exercise 1: Basic turtle operations

In the Interactions pane, type (or copy-paste) the following sequence of Java statements and answer the questions below.

World worldObj = new World();
Turtle turtle1 = new Turtle(worldObj);
System.out.println(turtle1);

Questions

  1. What is printed out ?

  2. What do the values represent?

  3. Is this very meaningful to the average user?


Exercise 2: Set Turtle Name:

Add to the Turtle.java Class
Create a method that takes one String parameter and assigns a new name to the turtle:

visibility return_type setTurtleName( variable_type paramater)
{
   // note: there is a method in the Turtle class called setName()
   ////  your code here  //////
}

Exercise 3: Get the Turtle name and coordinates and return them in a string

Add to the Turtle.java Class
Create a method that returns the String: My turtle is named <turtle name> who can be presently found at the <X>,<Y> coordinates and is facing <Z> direction.

(so: if your turtle was named Myrtle and was at the coordinates 37, 125, and a heading of 45.5 degrees, your return string would be:
           My turtle is named Myrtle who can be presently found at the 37,125 coordinates  and is facing 45.5 direction.

visibility return_type getTurtleDescription( )
{
   // note: there are methods in the Turtle class called getName(), getXPos(), getYPos() and getHeading()
   // getName() returns a String
   // getXPos() and getYPos() both returns an integer
   // getHeading() retuns a double
   // keep this in mind when you write your code

   ////  your code here  //////

   return <your string goes here>
}


Exercise 4: Using the new methods in a complete Java program

You will now write a complete Java program that creates a Turtle in a new World. uses the setter method you wrote to set the name of the Turtle to any name of your choosing and then uses the getter method you wrote to print out the description of the Turtle requested in Exercise 3..

           
public class TurtleValues
{
  public static void main(String[] args)
  {
  /*  your code goes here */
  }
}