用java写设计一个类Shape(图形)包含求面积和周长的area()方法和perimeter()方法以及设置颜色的方法SetColor(),并设计其子类Circle(圆形)类、Rectangle(矩形)类,并分别实现相应的求面积和求周长的方法。每个类都要覆盖toString方法。
时间: 2024-03-21 15:38:10 浏览: 155
好的,下面是设计的代码:
```java
public class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
public double area() {
return 0;
}
public double perimeter() {
return 0;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape{" +
"color='" + color + '\'' +
'}';
}
}
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
@Override
public String toString() {
return "Circle{" +
"color='" + super.toString() + '\'' +
", radius=" + radius +
'}';
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(String color, double width, double height) {
super(color);
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
@Override
public double perimeter() {
return 2 * (width + height);
}
@Override
public String toString() {
return "Rectangle{" +
"color='" + super.toString() + '\'' +
", width=" + width +
", height=" + height +
'}';
}
}
```
以上就是基于 Java 设计的 Shape 类及其子类 Circle 和 Rectangle,每个子类都覆盖了基类的求面积、周长和 toString() 方法。你可以根据需要进行调整和扩展。
阅读全文