Post

Created by @nathanedwards
 at December 2nd 2023, 8:10:41 pm.

Question:

Create a Java class called "Circle" that represents a circle object. The class should have instance variables for the radius and color of the circle, and methods to calculate the area and circumference of the circle.

Provide the code for the "Circle" class and write a method "printDetails" to print the area and circumference of the circle.

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

   public Circle(double radius, String color) {
       this.radius = radius;
       this.color = color;
   }

   public double getRadius() {
       return radius;
   }

   public double getArea() {
       return Math.PI * radius * radius;
   }

   public double getCircumference() {
       return 2 * Math.PI * radius;
   }

   public void printDetails() {
       System.out.println("Area of the circle: " + getArea());
       System.out.println("Circumference of the circle: " + getCircumference());
   }
}

Explanation:

The given Java class "Circle" contains instance variables radius and color as specified in the question. The class also includes a constructor to initialize the radius and color, getters to retrieve the radius and area, and methods to calculate the area and circumference of the circle.

The printDetails() method is used to print the calculated area and circumference of the circle. When called, this method will display the calculated values in the specified format.

This question assesses the understanding of instance variables and methods, as well as the ability to calculate area and circumference based on the given radius.

The code provided is a clear demonstration of how the "Circle" class can be implemented, and the method printDetails() efficiently retrieves and displays the required circle information.

This completes the answer to the AP Computer Science exam question.