CPSC 124, Spring 2014
Sample Answers to Quiz #7

Question 1. Suppose that the definition of a class begins with the line

public class Foo extends Bar {

Explain what this means, and state what is the "subclass" and what is the "superclass" in this line.

Answer. This line declares Foo to be a subclass of Bar, making Bar a superclass of Foo. The effect is that all the methods and variables defined in Bar are "inherited" by Foo; that is, it is almost as if they were copied into the definition of Foo. Any instance of the class Foo is then an instance of Bar as well, and an object of type Foo can be assigned to a variable of type Bar. Foo can add new variables and methods to those that it inherits from Bar, and it can "override" instance methods; that is, it can provide a new definition for an instance method.

Question 2. Explain the special variable this. Where is it used, and what does it mean?

Answer. this is a special variable that can be used in the instance methods and constructors of any class. It contains a pointer the the "current object," that is, to the object that contains the method in which this is used. It makes it possible to refer to instance variables and instance methods of the object even when hidden by another variable or method of the same name. For example, this.name always refers to the instance variable named name in the current object. It can also be used an actual parameter, as in for example button.addActionListener(this).

(There is one other, more obscure use for this: It can be used in the very first command in the definition of a constructor to call another constructor in the same class. In that case, this looks like it is being used as a method instead of as a variable.)

Question 3. The class Counter, shown below, represents a counter that can only be incremented and evaluated. Write a subclass that represents a counter that has the same capabilities but that can also be reset to zero. The new class should have a method named reset that sets the value of the counter to zero when it is called.

public class Counter {
    protected int value = 0;
    public void increment() {
    public int getValue() {
        return value;


public class ResetableCounter extends Counter {

    public void reset() {
        value = 0;