用java编写程序,定义Shape抽象类,含有可能的常量,含有获取面积的抽象方法; 定义多个子类,如Triangle,Circle,Rectangle继承Shape类; 定义测试类,在测试类中,定义shape数组,实例化若干对象,然后遍历元素的名称和面积。
时间: 2024-05-07 14:16:38 浏览: 10
好的,这是一个关于Java编程的问题,我可以回答。您可以这样定义Shape抽象类:
```
public abstract class Shape {
public static final double PI = 3.1415926535; // 可能的常量
public abstract double getArea(); // 获取面积的抽象方法
}
```
然后定义多个子类,如Triangle、Circle、Rectangle继承Shape类:
```
public 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 getArea() {
return 0.5 * base * height;
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return PI * radius * radius;
}
}
public 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 getArea() {
return width * height;
}
}
```
最后在测试类中,可以这样实例化若干对象,遍历元素的名称和面积:
```
public class TestShape {
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(4, 5);
for (Shape shape : shapes) {
System.out.println("The area of " + shape.getClass().getSimpleName() + " is " + shape.getArea());
}
}
}
```
当然,这只是一个简单的示例,实际上还可以定义更多的子类,实现更多的功能。