In: Computer Science
In java
Given the following UML class diagram, implement the class as
described by the model. Use your best judgement when implementing
the code inside of each method.
+------------------------------+
| Circle |
+------------------------------+
| - radius : double = 1.0 |
+------------------------------+
| + Circle(radius : double) |
| + getRadius() : double |
| + setRadius(radius : double) |
| + area() : double |
| + perimeter() : double |
+------------------------------+
The following information might also be useful:
Formula for area of a circle with radius r:
A = πr^2
Formula for perimeter of a circle with radius r:
P = π2r
Below is the JAVA code I hope that i have provided sufficient comments for your better understanding Note that I have done proper indentation but this code is automatically left alligned on this interface
import java.util.Scanner;
class Circle
{
private double radius;
static final double PI =3.14;
//constant
public Circle() //default
constructor
{
radius = 1;
}
public Circle (double rad) //parameterized
constructor
{
radius = rad;
}
public double getRadius()
{
return radius;
}
public void setRadius(double r)
{
radius = r;
}
double area()
{
return PI*radius*radius;
}
double perimeter()
{
return 2*PI*radius;
}
public static void main(String [] args)
{
Scanner input = new
Scanner(System.in);
Circle c1 = new Circle(); //default
constructor invoked
System.out.println("Enter the
radius :");
double r =
input.nextDouble();
c1.setRadius(r);
System.out.println("Area of circle
is :" + c1.area());
System.out.println("Perimeter of
circle is :" + c1.perimeter());
}
}
Below is the screenshot of output