java计算多个图形面积
时间: 2023-11-04 13:15:22 浏览: 50
可以使用面向对象编程思想,抽象出图形类,然后分别创建多个图形对象,并调用计算面积的方法。以下是一个简单的示例:
```
public abstract class Shape {
public abstract double getArea();
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(2.0);
shapes[1] = new Rectangle(3.0, 4.0);
shapes[2] = new Rectangle(5.0, 6.0);
double totalArea = 0.0;
for (Shape shape : shapes) {
totalArea += shape.getArea();
}
System.out.println("Total area: " + totalArea);
}
}
```
在上面的示例中,我们定义了一个抽象的 `Shape` 类,并在其内部定义了一个抽象的 `getArea` 方法。然后我们分别创建了 `Circle` 和 `Rectangle` 类继承 `Shape` 类,并实现了 `getArea` 方法。在 `Main` 类中,我们创建了三个不同的图形对象并存储在数组中,然后遍历该数组并累加每个图形对象的面积,最终输出总面积。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)