(5)定义Shape接口实现多态。 interface Shape void draw(); void erase(); Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图
时间: 2024-01-22 17:21:30 浏览: 21
下面是实现代码:
```
import java.util.Random;
interface Shape {
void draw();
void erase();
}
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle...");
}
public void erase() {
System.out.println("Erasing a circle...");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Drawing a square...");
}
public void erase() {
System.out.println("Erasing a square...");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("Drawing a triangle...");
}
public void erase() {
System.out.println("Erasing a triangle...");
}
}
public class NewShapes {
public static void main(String[] args) {
Random rand = new Random();
Shape[] shapes = new Shape[9];
for (int i = 0; i < 9; i++) {
int shapeType = rand.nextInt(3);
switch (shapeType) {
case 0:
shapes[i] = new Circle();
break;
case 1:
shapes[i] = new Square();
break;
case 2:
shapes[i] = new Triangle();
break;
}
shapes[i].draw();
shapes[i].erase();
System.out.println();
}
}
}
```
在这个程序中,我们定义了一个 `Shape` 接口,其中包含了两个方法 `draw()` 和 `erase()`。然后我们定义了三个类 `Circle`、`Square` 和 `Triangle`,它们都实现了 `Shape` 接口,并且分别实现了 `draw()` 和 `erase()` 方法。
在 `NewShapes` 类中,我们使用了 `Random` 类来随机生成 9 个不同的图形,并且对于每个图形,都调用了它们的 `draw()` 和 `erase()` 方法。由于每个图形都实现了 `Shape` 接口,因此可以将它们存储在 `Shape` 类型的数组中,并且可以通过数组来调用它们的方法。