CS 1401, Quiz 12

Date: Monday, November 19, 2007
Name (please type legibly, ideally in block letters): ______________________________________________________________________
Class section (9:30 am or 11:30 am):_______________________________

1. Mark what new material is covered and what is not covered in Chapter 12:

2. Define a class Coat in which each object has a color and a size (in inches). Do not forget to include a constructor method, accessor methods, and mutator methods.


Solution:

public class Coat{
  protected String color;
  protected double size;
  public Coat(String acolor, double asize){color = acolor; size = asize;}
  public String getColor(){return color;}
  public double getSize(){return size;}
  public void setColor(String newColor){color = newColor;}
  public void setSize(double newSize){size = newSize;}
}

3. Considering Coat as a superclass, define a subclass CoatForExport in which there is also an additional method returning the size in centimeters. Reminder: 1 in = 2.54 cm, so to get the size in cm, you need to multiply the size in inches by 2.54.


public class CoatForExport extends Coat{
  public CoatForExport(String acolor, double asize)
    {super(acolor, asize);}
  public double sizeInCm(){return size * 2.54;}
}

4. In the main method, define a new object of type CoatForExport with your favorite color and size 10 inches, and return its size in cm. Trace your code step-by-step.

Solution:

CaotForExport niceCoat = new CoatForExport("blue", 10.0);
System.out.println(niceCoat.sizeInCm());

Tracing:

on the first line, we call a constructor method:

 -----------------
|  -------------  |
| |   blue      | |
|  ------------   |
|     acolor      |
|  ------------   |
| |   10.0     |  |
|  ------------   |
|     asize       |
|-----------------|
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
 -----------------
  CoatForExport

this method, in its turn, calls a constructor method of the superclass:

 -----------------
|  -------------  |
| |   blue      | |
|  ------------   |
|     acolor      |
|  ------------   |
| |   10.0     |  |
|  ------------   |
|     asize       |
|-----------------|
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
 -----------------
     Coat

after the first line, we get a new object

 -----------------
|  -------------  |
| |   blue      | |
|  ------------   |
|     color       |
|  ------------   |
| |   10.0     |  |
|  ------------   |
|     size        |
|-----------------|

     niceCoat

after the second line, we call the method sizeInCm, which computes the
value 10.0 * 2.54 = 25.4. Then, we print this value.