Write a java class encapsulating the concept of a circle, assuming a circle has
ID: 3924339 • Letter: W
Question
Write a java class encapsulating the concept of a circle, assuming a circle has the following attributes: a Point representing the center of the circle, and a double representing the radius of the circle. Include a constructor, the accessor methods, the mutator methods, toString and equals methods, a method to compute the area of the circle and a method to compute the perimeter of the circle. Write a client class to test all the methods in your class.
Area = 2*p *radius
Perimeter = p*radius2
Hint: Can radius be < 0?
Hint: Be sure to maintain encapsulation.
Explanation / Answer
CirclePointTest.java
import java.util.Scanner;
public class CirclePointTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first circle radius: ");
double radius = scan.nextDouble();
Point p = new Point();
p.setRadius(radius);
System.out.println(p.toString());
System.out.println("Enter the second circle radius: ");
double radius2 = scan.nextDouble();
Point p1 = new Point();
p1.setRadius(radius2);
System.out.println(p1.toString());
System.out.println("First and second circles are equal: "+p1.equals(p));
}
}
Point.java
public class Point {
private double radius ;
public Point(int radius){
if(radius>= 0){
this.radius = radius;
}
}
public Point(){
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
if(radius>= 0){
this.radius = radius;
}
}
public double getArea(){
return 2 * Math.PI * radius;
}
public double getPerimeter(){
return 2 * Math.PI * radius;
}
public String toString(){
return "Radius: "+getRadius()+" Area: "+getArea()+" Perimeter: "+getPerimeter();
}
public boolean equals(Point p){
if(this.radius == p.radius){
return true;
}
return false;
}
}
Output:
Enter the first circle radius:
4
Radius: 4.0 Area: 25.132741228718345 Perimeter: 25.132741228718345
Enter the second circle radius:
3
Radius: 3.0 Area: 18.84955592153876 Perimeter: 18.84955592153876
First and second circles are equal: false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.