编写程序,定义一个接口 Compute,声明计算周长calgirth()和面积calarea ()的方法,然后定义一个长方形类RRect和圆类Circle,两个类都实现接口 Compute,最后编写测试类进行测试
时间: 2024-05-02 10:19:57 浏览: 87
好的,这是一个关于编写程序的问题,我可以回答。
首先,定义接口 Compute,声明计算周长 calgirth() 和面积 calarea() 的方法:
```
public interface Compute {
public double calgirth();
public double calarea();
}
```
然后,定义长方形类 RRect 和圆类 Circle,两个类都实现接口 Compute:
```
public class RRect implements Compute {
private double length;
private double width;
public RRect(double length, double width) {
this.length = length;
this.width = width;
}
public double calgirth() {
return 2 * (length + width);
}
public double calarea() {
return length * width;
}
}
public class Circle implements Compute {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calgirth() {
return 2 * Math.PI * radius;
}
public double calarea() {
return Math.PI * radius * radius;
}
}
```
最后,编写测试类进行测试:
```
public class Test {
public static void main(String[] args) {
RRect r = new RRect(3, 4);
Circle c = new Circle(5);
System.out.println("The girth of RRect is " + r.calgirth() + ", and the area is " + r.calarea() + ".");
System.out.println("The girth of Circle is " + c.calgirth() + ", and the area is " + c.calarea() + ".");
}
}
```
输出结果应该为:
```
The girth of RRect is 14.0, and the area is 12.0.
The girth of Circle is 31.41592653589793, and the area is 78.53981633974483.
```
希望这个回答能够帮到您!
阅读全文