用Java实现用自定义方法, 分别求三角形、矩形和圆的面积。在主函数中调用自定义方法, 并返回面积
时间: 2024-09-08 11:00:50 浏览: 91
在Java中,你可以创建一个名为Shape的抽象基类,然后为具体的形状如Triangle(三角形)、Rectangle(矩形)和Circle(圆)分别创建子类,并重写计算面积的方法。下面是一个简单的示例:
```java
// 创建抽象基类 Shape
abstract class Shape {
abstract double getArea();
}
// 三角形类 Triangle
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double getArea() {
return 0.5 * base * height;
}
}
// 矩形类 Rectangle
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double getArea() {
return length * width;
}
}
// 圆类 Circle
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double getArea() {
return Math.PI * Math.pow(radius, 2);
}
}
public class Main {
public static void main(String[] args) {
// 创建并初始化每个形状的对象
Triangle triangle = new Triangle(4, 6);
Rectangle rectangle = new Rectangle(5, 7);
Circle circle = new Circle(3);
// 调用各自的面积计算方法
double triangleArea = triangle.getArea();
double rectangleArea = rectangle.getArea();
double circleArea = circle.getArea();
System.out.println("三角形的面积: " + triangleArea);
System.out.println("矩形的面积: " + rectangleArea);
System.out.println("圆的面积: " + circleArea);
阅读全文