设计一个 Shape 抽象类,包括:~ 成島変量包括顔色 color 和是否填充 filled (boolean),默込 値力 false i 対 color 和 filled 迸行初始化的枸造方法;← 计算面积 getArea0的抽象方法; 计算周长 getLength的抽象方法;く 设计一个接口 Colorable,包括一个void howToColor(String color)的方法。← 设计一个类 Square,继承 Shape 类,实现 Colorable 接口,。 并包含成変量 length; ← toString(方法,輸出 Square 的面和周K。创建一个测试类,创建一个 Square 对象并输出。
时间: 2023-06-14 22:02:46 浏览: 126
下面是 Shape 抽象类、Colorable 接口、Square 类和测试类的实现:
```java
// Shape 抽象类
abstract class Shape {
protected String color;
protected boolean filled;
public Shape(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getLength();
}
// Colorable 接口
interface Colorable {
void howToColor(String color);
}
// Square 类
class Square extends Shape implements Colorable {
private double length;
public Square(double length, String color, boolean filled) {
super(color, filled);
this.length = length;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getArea() {
return length * length;
}
public void howToColor(String color) {
setColor(color);
System.out.println("Color the square with " + color);
}
public String toString() {
return "Square[length=" + length + ",color=" + color + ",filled=" + filled + "]";
}
}
// 测试类
public class TestShape {
public static void main(String[] args) {
Square square = new Square(5, "red", true);
System.out.println(square);
System.out.println("Area: " + square.getArea());
System.out.println("Perimeter: " + square.getLength());
square.howToColor("blue");
System.out.println(square);
}
}
```
输出结果如下:
```
Square[length=5.0,color=red,filled=true]
Area: 25.0
Perimeter: 5.0
Color the square with blue
Square[length=5.0,color=blue,filled=true]
```
阅读全文