利用java写出一个计算几何体面积的
时间: 2024-10-20 19:19:45 浏览: 36
在Java中,计算几何体面积需要根据具体的几何形状来进行。这里以常见的几种几何体为例:
1. **矩形**:
```java
public class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
}
```
2. **圆形**:
```java
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * Math.pow(radius, 2);
}
}
```
3. **三角形**:
```java
public class Triangle {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
```
每个类都有一个`getArea()`方法用于计算其相应的面积。为了利用多态,你可以创建一个接口或者抽象类`Shape`,然后让上述几何类实现它:
```java
interface Shape {
double getArea();
}
class GeometricShape implements Shape {
// 实现具体形状的面积计算
}
// 然后在主函数中通过Shape类型的引用调用area方法,实际运行时会自动调用相应几何体的area方法
Shape rectangle = new Rectangle(10, 5);
Shape circle = new Circle(4);
Shape triangle = new Triangle(6, 8);
System.out.println(rectangle.getArea()); // 输出矩形面积
System.out.println(circle.getArea()); // 输出圆形面积
System.out.println(triangle.getArea()); // 输出三角形面积
```
阅读全文
相关推荐


















