CS 1401, Quiz 12, Solutions

Date: Tuesday, April 17, 2007
Name (please type legibly, ideally in block letters): ______________________________________________________________________
Class section (9:00 am or 10:30 am):_______________________________

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

2. Define a class Health in which each object has a name and a (body) temperature (in F). Do not forget to include a constructor method, accessor methods, and mutator methods.


Solution:

public class Health{
  protected String name;
  protected double temp;
  public Health(String aname, double atemp){name = aname; temp = atemp;}
  public String getName(){return name;}
  public double getTemp(){return temp;}
  public void setName(String newName){name = newName;}
  public void setTemp(double newTemp){temp = newTemp;}
}

3. Considering Health as a superclass, define a subclass ExtendedHealth in which there is also a possibility of changing and returning body temperature in C. Reminder: F = 32 + 1.8 * C and C = (F - 32)/1.8.


public class ExtendedHealth extends Health{
  public ExtendedHealth(String aname, double atemp)
    {super(aname, atemp);}
  public double getC(){return (temp - 32.0)/1.8:}
  public void setC(double tempC){temp = 32 + 1.8 * tempC;}
}

4. In the main method, define a new object of type ExtendedHealth with your name and perfect body temperature 97.9, and return its perfect body temperature in C (should be 36.6). Trace your code step-by-step.

Solution:

ExtendedHealth i = new ExtendedHealth("Carlos Acosta", 97.9);
System.out.println(i.getC());

Tracing:

on the first line, we call a constructor method:

 -----------------
|  -------------  |
| |Carlos Acosta| |
|  ------------   |
|     aname       |
|  ------------   |
| |   97.9     |  |
|  ------------   |
|     atemp       |
|-----------------|
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
 -----------------
  ExtendedHealth

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

 -----------------
|  -------------  |
| |Carlos Acosta| |
|  ------------   |
|     aname       |
|  ------------   |
| |   97.9     |  |
|  ------------   |
|     atemp       |
|-----------------|
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
|                 |
 -----------------
      Health

after the first line, we get a new object

 -----------------
|  -------------  |
| |Carlos Acosta| |
|  ------------   |
|     name        |
|  ------------   |
| |   97.9     |  |
|  ------------   |
|     temp        |
|-----------------|

        i

after the second line, we call the method getC, which computes the value
(97.9 - 32)/1.8 as 36.6. Then, we print this value.