Java Encapsulation: Implementing a circle class with getter, setter, and calculation methods
Write a Java program to create a class called Circle with a private instance variable radius. Provide public getter and setter methods to access and modify the radius variable. However, provide two methods called calculateArea() and calculatePerimeter() that return the calculated area and perimeter based on the current radius value.
Sample Solution:
Java Code:
Output:
Circle Radius: 7.0 Circle Area: 153.93804002589985 Circle Perimeter: 43.982297150257104
Explanation:
In the above exercise,
In this code, the Circle class encapsulates the private instance variable radius. The getRadius() and setRadius() methods are public getter and setter methods that allow other classes to access and modify radius values, respectively.
Additionally, the Circle class provides two public methods calculateArea() and calculatePerimeter() that calculate and return the area and perimeter of the circle. These methods are based on the current radius value. These methods use the formula Math.PI*radius*radius for area calculation and 2*Math.PI*radius for perimeter calculation.
In the Main class, an object circle of the Circle class is created. The circle radius is set using the setRadius() method, and then retrieved using the getRadius() method.
The area and perimeter of the circle are calculated using the calculateArea() and calculatePerimeter() methods, respectively, and printed using System.out.println().
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program where the "Circle" class prevents setting a negative radius.
- Write a Java program where the "Circle" class calculates the circumference using a separate method.
- Write a Java program where the "Circle" class includes a method to determine if one circle can fit inside another.
- Write a Java program where the "Circle" class supports resizing the radius with a scale factor.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus
PREV : Implementing an Employee Class with Getter and Setter Methods.
NEXT : Implementing Car Class with Getter and Setter Methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.