设计一个名为 Shape 的抽象类。 因为形状未知,无法计算面积,因此将 getArea 方法定义为抽象方法,子类实现抽象方法。toString方法输出Shape[color=XXX],返回值为String 子类使用构造方法,public 方法名(String int int) 题目要求 根据题目描述及类图,完成Shape抽象类及其子类。 注: 在main方法当中测试类。color为private(用Java语言)
时间: 2023-11-27 19:54:15 浏览: 63
以下是根据题目描述及类图所完成的 Shape 抽象类及其子类:
```java
abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
public String toString() {
return "Shape[color=" + color + "]";
}
public abstract double getArea();
}
class Circle extends Shape {
private int radius;
public Circle(String color, int radius) {
super(color);
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public String toString() {
return "Circle[color=" + super.toString() + ",radius=" + radius + "]";
}
}
class Rectangle extends Shape {
private int width;
private int height;
public Rectangle(String color, int width, int height) {
super(color);
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public String toString() {
return "Rectangle[color=" + super.toString() + ",width=" + width + ",height=" + height + "]";
}
}
```
在 main 方法中进行测试:
```java
public static void main(String[] args) {
Shape circle = new Circle("Red", 5);
System.out.println(circle.toString());
System.out.println("Area: " + circle.getArea());
Shape rectangle = new Rectangle("Blue", 4, 6);
System.out.println(rectangle.toString());
System.out.println("Area: " + rectangle.getArea());
}
```
输出结果:
```
Circle[color=Shape[color=Red],radius=5]
Area: 78.53981633974483
Rectangle[color=Shape[color=Blue],width=4,height=6]
Area: 24.0
```
阅读全文