用java编写一个抽象类表示形状,其中有一个求面积的抽象方法。继承该抽象类分别编写三角形、园,矩形类,创建一个数组存放创建的各类图形对象,输出图形面积。
时间: 2024-05-07 15:15:24 浏览: 57
抽象类Shape:
```
public abstract class Shape {
public abstract double getArea();
}
```
三角形类Triangle:
```
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getBase() {
return base;
}
public double getHeight() {
return height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
```
圆类Circle:
```
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
矩形类Rectangle:
```
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
@Override
public double getArea() {
return width * height;
}
}
```
测试代码:
```
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Triangle(3, 4);
shapes[1] = new Circle(5);
shapes[2] = new Rectangle(6, 7);
for (Shape shape : shapes) {
System.out.println("面积为:" + shape.getArea());
}
}
}
```
输出结果:
```
面积为:6.0
面积为:78.53981633974483
面积为:42.0
```
阅读全文