CS 1401, Quiz 7

Date: Monday, October 23, 2006
Name (please type legibly, ideally in block letters): ______________________________________________________________________

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

2-4.

2. Define a class Circle whose elements are circular creatures; each creature is characterized by its name and its radius R. Your class should contain a constructor method, accessor methods, mutator methods, and methods for computing the diameter 2R, the circumference 2 Pi R, and the area Pi R^2.

Solution:

public class Circle{
  private String name;
  private double radius;

  public Circle(String aname, double araduis){
    name = aname, radius = aradius;}

  public String getName(){return name;}

  public double getRadius(){return radius;}

  public void setName(String newName){name = newName;}

  public void setRadius(double newRadius){radius = newRadius;}

  public double diameter(){return 2.0 * radius;}

  public double circumference(){return 2.0 * Math.Pi * radius;}

  public double area(){return Math.Pi * radius * radius;}
}
3. Use your class in the main method to define a new circular creature "Circy" with radius 3.0. Compute and print Circy's diameter; then, simulate how Circy grows: replace the radius with the larger value 4.0, and compute and print its new diameter.

Solution:

Circle circy = new Circle("Circy", 3.0);
double diam = circy.diameter();
System.out.println(diam);
circy.setRadius(4.0);
diam = circy.diameter();
System.out.println(diam);
4. Trace your program step-by-step.

Solution (in brief):

on the first line, we call a constructor method:

 --------------
|  ----------  |
| |  Circy   | |
|  ----------  |
|    aname      |
|  ----------  |
| |   3.0    | |
|  ----------  |
|   aradius    |
 --------------
|              |
|              |
|              |
|              |
|              |
|              |
|              |
|              |
 --------------
    Circle

after the first line, we get a new object

 --------------
|  ----------  |
| |  Circy   | |
|  ----------  |
|    name      |
|  ----------  |
| |   3.0    | |
|  ----------  |
|    radius    |
 --------------
    circy

after the second line, we get

 ----------
|   6.0    |
 ----------
    diam

at the third line, we print 6.0 to the screen

after the fourth line, the object changes to:

 --------------
|  ----------  |
| |  Circy   | |
|  ----------  |
|    name      |
|  ----------  |
| |   4.0    | |
|  ----------  |
|    radius    |
 --------------
    circy

after the fifth line, we change the value of the variable diam:

 ----------
|   8.0    |
 ----------
    diam

on the sixth line, we print 8.0 to the screen