定义一个圆形使用Circle类,半径为r,并且get/set方法,showArea方法:打印圆形面积,showPerimeter方法:打印圆形周长 定义测试类。
时间: 2024-05-09 22:20:57 浏览: 174
Circle类的代码如下:
```java
public class Circle {
private double radius;
private final double PI = 3.14159265359;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return PI * radius * radius;
}
public double getPerimeter() {
return 2 * PI * radius;
}
public void showArea() {
System.out.println("The area of the circle with radius " + radius + " is " + getArea());
}
public void showPerimeter() {
System.out.println("The perimeter of the circle with radius " + radius + " is " + getPerimeter());
}
}
```
测试类的代码如下:
```java
public class CircleTest {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
circle.showArea();
circle.showPerimeter();
circle.setRadius(7.5);
circle.showArea();
circle.showPerimeter();
}
}
```
运行结果如下:
```
The area of the circle with radius 5.0 is 78.53981633974483
The perimeter of the circle with radius 5.0 is 31.41592653589793
The area of the circle with radius 7.5 is 176.71458676442586
The perimeter of the circle with radius 7.5 is 47.12388980384689
```
阅读全文