使用java语言,定义一个父类形状,其中包括求形状面积的方法。继承该类定义三角形,矩形,圆。分别创建一个三角形、矩形、圆,将各类图形的面积输出。
时间: 2023-12-03 19:47:26 浏览: 50
下面是Java代码实现:
```
public class Shape {
public double area() {
return 0.0;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}
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 area() {
return width * height;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(3, 4);
Rectangle rectangle = new Rectangle(5, 6);
Circle circle = new Circle(7);
System.out.println("Triangle area: " + triangle.area());
System.out.println("Rectangle area: " + rectangle.area());
System.out.println("Circle area: " + circle.area());
}
}
```
输出结果为:
```
Triangle area: 6.0
Rectangle area: 30.0
Circle area: 153.93804002589985
```
阅读全文