定义一个shape 抽象类,利用它作为基类派生出 Rectangle、Circle 等具体形状类,已知具体形状关均具有两个方法GetArea()和 GetColor(),分别用来得到形状的面积和顾色。最后编写一个测试程序对产生的类的功能进行验证。java
时间: 2023-05-21 17:02:47 浏览: 211
好的,以下是定义一个shape抽象类,以及派生出Rectangle和Circle类的代码:
```
abstract class Shape {
public abstract double getArea();
public abstract String getColor();
}
class Rectangle extends Shape {
private double width;
private double height;
private String color;
public Rectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
public double getArea() {
return width * height;
}
public String getColor() {
return color;
}
}
class Circle extends Shape {
private double radius;
private String color;
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public double getArea() {
return Math.PI * radius * radius;
}
public String getColor() {
return color;
}
}
```
接下来是测试程序的代码:
```
public class Test {
public static void main(String[] args) {
Shape rectangle = new Rectangle(3, 4, "red");
Shape circle = new Circle(5, "blue");
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle color: " + rectangle.getColor());
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle color: " + circle.getColor());
}
}
```
运行测试程序后,输出结果如下:
```
Rectangle area: 12.0
Rectangle color: red
Circle area: 78.53981633974483
Circle color: blue
```
这表明我们定义的抽象类和具体类都能够正常工作。
阅读全文