用java语言(1)编写 Shape 接口,接口中声明 computeArea 0方法。 (2)定义Rectangle 类和 Circle 类实现 Shape 接口。 (3)编写 Rectangle 类和 Circle 类的测试程序,使用接口回调, 执行computeArea 0()方法,给出网半径(如下=3)和矩形长与宽(如,length= 5 ,计算它们的面积,其中pi =3.14。
时间: 2023-05-23 07:03:04 浏览: 111
请看以下代码:
Shape.java
```
public interface Shape {
public double computeArea();
}
```
Rectangle.java
```
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double computeArea() {
return length * width;
}
}
```
Circle.java
```
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double computeArea() {
return Math.pow(radius, 2) * Math.PI;
}
}
```
Test.java
```
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
shapes[0] = new Rectangle(5, 3);
shapes[1] = new Circle(3);
for (Shape shape : shapes) {
System.out.println("Area: " + shape.computeArea());
}
}
}
```
在这个测试程序中,我们创建了Rectangle和Circle对象,并将它们存储在一个Shape数组中,然后使用接口回调来调用每个对象的computeArea方法,并打印出它们的面积。输出应该是:
```
Area: 15.0
Area: 28.274333882308138
```
阅读全文