编写程序,定义一个接口Compute,声明计算周长calgirth()和面积calarea ()的方法,然后定义一个长方形类RRect和圆类Circle,两个类都实现接口Compute,最后编写测试类进行测试
时间: 2024-02-12 14:04:49 浏览: 145
好的,代码如下:
```java
// 接口Compute
interface Compute {
double calgirth(); // 计算周长
double calarea(); // 计算面积
}
// 长方形类RRect
class RRect implements Compute {
double length;
double width;
public RRect(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calgirth() {
return 2 * (length + width);
}
@Override
public double calarea() {
return length * width;
}
}
// 圆类Circle
class Circle implements Compute {
double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calgirth() {
return 2 * Math.PI * radius;
}
@Override
public double calarea() {
return Math.PI * radius * radius;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
RRect rRect = new RRect(2, 3);
System.out.println("长方形的周长:" + rRect.calgirth()); // 长方形的周长:10.0
System.out.println("长方形的面积:" + rRect.calarea()); // 长方形的面积:6.0
Circle circle = new Circle(4);
System.out.println("圆的周长:" + circle.calgirth()); // 圆的周长:25.132741228718345
System.out.println("圆的面积:" + circle.calarea()); // 圆的面积:50.26548245743669
}
}
```
阅读全文