CSCI A202 - Introduction to Programming (II)

Final Exam Information

Sample Problem 4

Consider the following program written in a file Three.java:

class Turtles {
  public static void main(String[] args) {
    Turtle a = new ConfinedTurtle("Condor");     
    a.location(); 
    a.jump(30, 40); 
    a.location(); 
  } 
}

class Turtle {
  private int x, y;    
  private String name; 

  Turtle(String givenName) { name = givenName; } 

  void jump(int deltaX, int deltaY) {
    x += deltaX; y += deltaY; 
    System.out.println(name + 
      " jumped to (" + x + ", " + y + ") "); 
  } 
  void location() {
    System.out.println(name + 
      " located at (" + x + ", " + y + ") "); 
  } 
}

class ConfinedTurtle extends Turtle {
  final static int LEFT = 0, RIGHT = 200, UP = 0, DOWN = 200; 
  void jump(int deltaX, int deltaY) {
    x += deltaX; y += deltaY; 
    if      (x < LEFT)  { x = LEFT;  } 
    else if (x > RIGHT) { x = RIGHT; } 
    if      (y < UP)    { y = UP;    } 
    else if (y > DOWN)  { y = DOWN;  } 
  } 
}
The program is written by a student that you are tutoring in Java.

He says that he basically wants to create a class Turtle and then extend it by creating a more specialized kind of turtle, that doesn't go out of a certain specified limits. (If the coordinates become too big or too small they are adjusted to the value of the limits).

He compiled this program and obtain 12 errors, some of which you can see listed below:

[1]  + Done                 emacs Three.java
school.cs.indiana.edu%javac Three.java
Three.java:3: Wrong number of arguments in constructor.
    Turtle a = new ConfinedTurtle("Condor");     
               ^
Three.java:27: No constructor matching Turtle() found in class Turtle.
class ConfinedTurtle extends Turtle {
      ^
Three.java:30: Variable x in class Turtle not accessible from class ConfinedTurtle.
    x += deltaX; y += deltaY; 
    ^
Three.java:30: Variable y in class Turtle not accessible from class ConfinedTurtle.
    x += deltaX; y += deltaY; 
                 ^
[snip]

12 errors
school.cs.indiana.edu%
He says that the the only thing he noticed is that making the instance variables x and y that the turtle uses for positioning protected seems to get rid of many errors, but not all.

Explain (as to the student) why protected eliminates the errors or at least why we have compilation errors related to the variables x and y.

Why do we have errors when we try to construct a turtle of the extended class type? Isn't the constructor "inherited" like variables and methods? If do you need to provide a constructor for the extended class consider the following constructor:

ConfinedTurtle(String givenName) { name = givenName; }
Would this work? Why or why not?