CPSC 124, Fall 2021: Sample Answers to Quiz #7

These are sample answers only.

Question 1. Explain the meaning and effect of "extends Fruit" in a class definition that begins:   public class Kumquat extends Fruit {...

Answer. Saying that "Kumquat extends Fruit" makes Kumguat a subclass of Fruit. Fruit must be a class that already exists. The subclass, Kumquat, inherits all the instance variables and methods from the Fruit class. It is then possible to add new variables and instance variables to class Kumquat, and to override (that is, provide different definitions for) methods that are defined in class Fruit.

Question 2. Given the classes Kumquat and Fruit from the previous problem, which of the following statements could be legal in Java? Explain.

    (1)  Fruit delicious = new Kumquat();
    
    (2)  Kumquat goodForYou = new Fruit();

Answer. Since Kumquat is a subclass of Fruit, any object of type Kumquat is also a Fruit. So it is legal to assign a Kumquat object to a Fruit varialbe. That is, (1) is legal (as long as class Kumquat has a constructor with no parameters). However, not every Fruit is a Kumquat, so (2) cannot be legal.

Question 3. A class contains the following setter method. What is the meaning of "this.name", and why is it necessary here?

   public void setName( String name ) {
       this.name = name;
   }

Answer. The special variable "this" refers to the object that contains the method. That object must have an instance variable named name. So, this.name refers to the value of the instance variable name in the object. It is necessary here because the method has a parameter named name, the same as the name of the instance variable. Inside the method, name by itself refers to the parameter, while this.name refers to the instance variable. The instance variable is hidden by the parameter, and this allows access to it.

Question 4. A class named PrintableDoc has an instance method print() that prints the document. A subclass named DocWithCount adds the ability to keep track of how many times the document was printed. Complete the following definition of class DocWithCount by adding three lines:

public class DocWithCount extends PrintableDoc {
    private int printCt = 0; // Number of times this document has been printed.
    public void print() { // Print document and increment counter.
    
    
    }
    public int getPrintCt() {
    
    }
}

Answer.

public class DocWithCount extends PrintableDoc {
    private int printCt = 0; // Number of times this document has been printed.
    public void print() { // Print document and increment counter.
        super.print();  // Call print method from superclass to print the document.
        printCt++;
    }
    public int getPrintCt() {
        return printCt;    
    }
}