CPSC 124, Spring 2017: Sample Answers to Quiz #6

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. Write a complete class definition containing: one private instance variable of type int, a method that can be used to add a specified value to that instance variable, and a getter method for reading the value of the variable.

Answer.

            public class RunningSum {
            
                private int sum;
                
                public void add(int number) {
                    sum = sum + number;
                }
                
                public int getSum() {
                    return sum;
                }
            
            }

(This question was repeated from the previous quiz.)

Question 2. Suppose c1 and c2 are two variables of type Color. Then you can test either  if (c1 == c2)  or  if (c1.equals(c2)). Explain the difference and what the difference has to do with pointers. What exactly is being tested in each case?

Answer. Since c1 and c2 are object variables, they can hold pointers to objects but do not hold the actual objects, which are stored in the heap. The test  if (c1 == c2)  tests whether c1 and c2 point to the same object. The test  if (c1.equals(c2))  on the other hand tests whether the objects that they point to represent the same color, that is, whether the two Color objects have the same red, green, blue, and alpha color component values. It is possible for the second test to be true even though the first test is false. (On the other hand, if  c1 == c2  is true, then  c1.equals(c2)  must also be true.)

Question 3. An important concept in object-oriented programming is constructors. What is a constructor? Explain the purpose of constructors. How is a constructor called? Give an example.

Answer. A constructor is a special kind of subroutine that is called using the new operator. The purpose of a constructor is to initialize an object that has just been created. For example, the expression new Color(100,150,200) calls a constructor in the Color class, which initializes the object by setting the red, green, and blue components of the color to 100, 150, and 200.