CS 140 - Homework 2 - Due Jan 28


Read sections 3.1 through 3.5 in your textbook.

Name:___________________________________

Answer the following questions:

  1. Explain the difference and similarites between a Java class and an object. You can either use real world examples or Java examples (such as the Turtle class).
  2. When creating a new object we usually create a reference to hold it. For example:

           World myWorld = new World();
    	 

    The reference myWorld is a mechanism that we can use to refer to the new World object created by the statement new World();

    Why doesn't it make sense to create an object without a reference to store it?  For example, just the command: new World();

  3. When we make a new Turtle object we pass a reference to a world to its class constructor. For example, look at the following code:
    	     World larrysWorld = new World();
    	     Turtle larryTheTurtle = new Turtle(larrysWorld);
    	  

    When we execute the statement

    		  new Turtle(larrysWorld);
    		

    we are passing a reference to the World created on the previous line. Why do we do this?

    What happens when you try to create a new Turtle object and you do not pass a reference to a World object to its constructor?

  4. When invoking a method on an object (the book calls it "Sending Messages to Objects") you first state the name of the object you wish to call the method on, then a ".", then the name of the method with an argument list in parenthesis.  For example:
    	  turtle1.forward(20);
    	

    Means that you want the Turtle object refered to by turtle1 to move forward 20 units. Why doesn't it make sense to make a call like this:

    	   forward(20);
    	
  5. What's the difference between the commands turtle1.turn(-45); and turtle1.turn(45);?
  6. Write a Java program to create a new world, place a single turtle in that world, make the turtle draw a pentagon with sides of length 150, then hide itself. Use the interactions pane in DrJava to do this and copy them into the space below. The end world should look something like this:
  7. Write a drawRectangle method for the Turtle class (similar to the drawSquare method on page 57 of your book) that takes two arguments: a length and width, and draws a rectangle of that specified length and width. Below is the header of the method you'll write:
           public void drawRectangle(int length, int width) {
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    	   
           }
    	
  8. Finally, construct a call to the drawRectangle method for a given Turtle object to draw a rectangle of length 100 and width 50:

© Rich Sharp (modified by Ed Harcourt)