用类计算圆形和三角形的面积的Java代码
时间: 2023-11-09 13:08:50 浏览: 32
好的,以下是用类计算圆形和三角形面积的Java代码示例:
```
class Shape {
private double radius;
private double base;
private double height;
public Shape(double r) {
radius = r;
}
public Shape(double b, double h) {
base = b;
height = h;
}
public double getCircleArea() {
return Math.PI * radius * radius;
}
public double getTriangleArea() {
return 0.5 * base * height;
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Shape(5.0);
Shape triangle = new Shape(3.0, 4.0);
System.out.println("圆形的面积: " + circle.getCircleArea());
System.out.println("三角形的面积: " + triangle.getTriangleArea());
}
}
```
请注意,这只是一个简单的示例代码,实际上还有很多不同的方法实现圆形和三角形的面积计算。