设计一个抽象类Shape,要求如下: 1、包含抽象方法:求面积的area()方法和求周长的perimeter()方法;以及普 通方法:设置颜色的setColor()方法和获取颜色的getColor方法(); 2、设计其子类Circle(圆形)类,包含属性半径r,并实现Shape类中的抽 象方法; 3、编写测试类ShapeTest,分别实现相应的求面积、求周长以及设置并获取 颜色的操作。
时间: 2024-02-06 20:09:23 浏览: 71
Java:使用抽象类定义一个“形状类”,能够计算周长和面积。
下面是代码实现:
```java
// Shape.java
public abstract class Shape {
private String color;
public abstract double area();
public abstract double perimeter();
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
// Circle.java
public class Circle extends Shape {
private double r;
public Circle(double r) {
this.r = r;
}
public double area() {
return Math.PI * r * r;
}
public double perimeter() {
return 2 * Math.PI * r;
}
}
// ShapeTest.java
public class ShapeTest {
public static void main(String[] args) {
Circle c = new Circle(3.0);
c.setColor("red");
System.out.println("The area of the circle is " + c.area());
System.out.println("The perimeter of the circle is " + c.perimeter());
System.out.println("The color of the circle is " + c.getColor());
}
}
```
运行结果如下:
```
The area of the circle is 28.274333882308138
The perimeter of the circle is 18.84955592153876
The color of the circle is red
```
阅读全文