229k views
1 vote
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. (The diameter of a circle is twice the radius, and the area of a circle is pi multiplied by the square of the radius. Use the Math class PI constant for this calculation.) Save the class as Circle.java.

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.

1 Answer

6 votes

class Circle {

private double radius;

public Circle() {

this.radius = 1.0;

}

public Circle(double radius) {

this.radius = radius;

}

public double getRadius() {

return radius;

}

public void setRadius(double radius) {

this.radius = radius;

}

public double getArea() {

return Math.PI * radius * radius;

}

}

public class TestCircle {

public static void main(String[] args) {

Circle circle1 = new Circle();

Circle circle2 = new Circle(5.0);

Circle circle3 = new Circle();

circle1.setRadius(3.0);

circle2.setRadius(10.0);

System.out.println("Circle 1: radius = " + circle1.getRadius() + ", area = " + circle1.getArea());

System.out.println("Circle 2: radius = " + circle2.getRadius() + ", area = " + circle2.getArea());

System.out.println("Circle 3: radius = " + circle3.getRadius() + ", area = " + circle3.getArea());

}

}

User Jimbo Jonny
by
7.4k points