CPSC 124, Spring 2013
Sample Answers to Quiz #7

Question 1. What is this (when you are writing a class definition in Java)?

Answer. This is a special predefined variable that can be used in constructors to refer to the object that is being constructed and in instance methods to refer the the object that contains that method.

Question 2. Suppose that Drawable is the name of a Java interface that specifies the method public void draw(Graphics g). What do you need to do to implement this interface in a class that you are writing? (There are two things to do!)

Answer. To implement the Drawable interface, you must, first, declare that the class implements the interface by saying, for example

public class MyClass implements Drawable { ...

and, second, you must provide a definition for the draw method in the class.

Question 3. For this problem, you should write a complete Java class definition. The name of the class is Adder. An object of type Adder stores the sum and the count of a sequence of numbers that are fed into it by calling an "add" method. The class contains two private instance variables to keep track of the sum and the count. The sum is of type double, and the count is of type int. It has a method add(x) that will add its parameter, x, to the sum and add 1 to the count. It has a method getCount() that returns the current value of the count and a method getSum() that returns the current value of the sum.

Answer.

public class Adder {

   private double sum;
   private int count;
   
   public void add(double x) {
      sum = sum + x;
      count = count + 1;
   }
   
   public int getCount() {
      return count;
   }
   
   public double getSum() {
      return sum;
   }

}