Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

a.Create a class named Circle with fields named radius, diameter, and area. Incl

ID: 3633491 • Letter: A

Question

a.Create a class named Circle with fields named radius, diameter, and area. Include a constructor that sets the radius to 1 and calculates the other two values. Also include methods named setRadius () and getRadius (). The setRadius () method not only sets the radius, it also calculates the other two values. (Remember that the diameter of a circle is twice the radius, and the area of a circle is pi multiplied by the square of the radius.) Save the class as Circle.java


b.Create a class named TestCircle whose main () method declares several Circle objects. Using the setRadius () method, assign one Circle a small radius value, and assign another a larger radius value. Do not assign a value to the radius of the third circle. Instead, retain the value assigned at construction. Display all the values for all the Circle objects. Save the application as TestCircle.java

--------------------------------------------------------------------------------

Explanation / Answer

1. Circle.java

public class Circle {
private double radius, diameter, area;
public Circle(){
radius = 1;
calc();
}

public void setRadius(double radius){
this.radius = Math.abs(radius);
calc();
}

public double getRadius(){
return this.radius;
}
public double getDiameter(){
return this.diameter;
}
public double getArea(){
return this.area;
}
private void calc(){
diameter = radius/2;
area = (22/7)*radius*radius;
}
}

2. TestCircle.java

public class TestCircle {
public static void main(String... args){
Circle c1 = new Circle();
Circle c2 = new Circle();
Circle c3 = new Circle();

c1.setRadius(2.0932);
c2.setRadius(22.234);

display(c1);
display(c2);
display(c3);
}

public static void display(Circle c){
System.out.println(" Radius " + c.getRadius());
System.out.println("Diameter" + c.getDiameter());
System.out.println("Area: " + c.getArea());
}
}