定义一个是shape抽象类,利用他作为基类派生出Retangle,circle等具体形状类,已知,具体形状类均具有两个方法Getarea,Getcolor,分别用来得到形状的面积和颜色,最后编写一个测试程序对产生的类的功能进行验证,用java实现
时间: 2023-05-27 18:06:46 浏览: 90
抽象类Shape的实现:
```java
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
public abstract double getArea();
public String getColor() {
return color;
}
}
```
Rectangle类的实现:
```java
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height, String color) {
super(color);
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
```
Circle类的实现:
```java
public class Circle extends Shape {
private double radius;
public Circle(double radius, String color) {
super(color);
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
```
测试程序的实现:
```java
public class Test {
public static void main(String[] args) {
Shape shape1 = new Rectangle(5, 10, "red");
Shape shape2 = new Circle(3, "blue");
System.out.println("The area of the rectangle is " + shape1.getArea());
System.out.println("The color of the rectangle is " + shape1.getColor());
System.out.println("The area of the circle is " + shape2.getArea());
System.out.println("The color of the circle is " + shape2.getColor());
}
}
```
输出结果:
```
The area of the rectangle is 50.0
The color of the rectangle is red
The area of the circle is 28.274333882308138
The color of the circle is blue
```
阅读全文