CPSC 124, Fall 2001
Quiz #5, October 22

This is the fifth quiz in CPSC 124: Introductory Programming.


Question 1: What is the relationship between objects and classes ?

Answer: Classes are used to create objects. The non-static variable declarations and non-static method definitions in the class specify the instance variables and methods that the objects will contains. The objects are said to be "instances" of the class or to "belong" to the class. From another point of view, a class specifies the common properties of a set of objects, namely all the objects that are instances of that class.


Question 2: A variable in Java can never hold an actual object. Instead, it holds a "pointer." What is a pointer? Where is the actual object?

Answer: In Java, all objects are stored in a certain part of memory known as the heap. A pointer to an object is just the address of the object in memory. Although a variable does not actually hold an object, it holds enough information to find the object.


Question 3: What is the new operator, and what does it have to do with constructors ? Give an example of using the new operator.

Answer: The new operator is used to create new objects. It is used to call constructors, which are special subroutines in a class whose purpose is to create and initialize objects. For example, in the statement "myDice = new PairOfDice(3,4);", a new object belonging to the class PairOfDice is created and a pointer to that object is stored in the variable myDice.


Question 4: For this problem, you should write a very simple but complete class. The class represents a counter than counts 0, 1, 2, 3, 4,.... The name of the class should be Counter. It has one private instance variable representing the value of the counter. It has two instance methods: increment() adds one to the counter, and getValue() returns the current counter value. Write a complete definition for the class Counter.

Answer:

          public class Counter {
          
             private int count;  // Current value of counter.
                                 // (Note:  This is automatically
                                 // initialized to the default
                                 // value, zero.)
                                 
             public void increment() {   // Adds 1 to counter.
                count++;
             }
             
             public int getValue() {     // Returns current counter value.
                return count;
             }
             
         }

David Eck, eck@hws.edu