、包含抽象方法:求面积的area()方法和求周长的perimeter()方法;以及普 通方法:设置颜色的setColor()方法和获取颜色的getColor方法(); 2、设计其子类Circle(圆形)类,包含属性半径r,并实现Shape类中的抽 象方法; 3、编写测试类ShapeTest,分别实现相应的求面积、求周长以及设置并获取 颜色的操作。
时间: 2024-02-03 07:15:22 浏览: 78
1. Shape类的代码:
```java
public abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
public abstract double area();
public abstract double perimeter();
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
```
2. Circle类的代码:
```java
public class Circle extends Shape {
private double r;
public Circle(String color, double r) {
super(color);
this.r = r;
}
@Override
public double area() {
return Math.PI * r * r;
}
@Override
public double perimeter() {
return 2 * Math.PI * r;
}
}
```
3. ShapeTest类的代码:
```java
public class ShapeTest {
public static void main(String[] args) {
Circle circle = new Circle("red", 5.0);
System.out.println("Circle area: " + circle.area());
System.out.println("Circle perimeter: " + circle.perimeter());
System.out.println("Circle color: " + circle.getColor());
circle.setColor("blue");
System.out.println("Circle color: " + circle.getColor());
}
}
```
输出结果:
```
Circle area: 78.53981633974483
Circle perimeter: 31.41592653589793
Circle color: red
Circle color: blue
```
阅读全文