用java 定义Shape接口实现多态。 interface Shapef void draw0; void erase@; Circle类、Square类、Triangle类实现Shape 编写程序NewShapes.java,利用Random 类实现随机9次调用不同图形类绘图。
时间: 2024-01-22 16:20:13 浏览: 143
下面是对应的接口和类的代码:
```java
interface Shape {
void draw();
void erase();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Draw a Circle.");
}
@Override
public void erase() {
System.out.println("Erase a Circle.");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Draw a Square.");
}
@Override
public void erase() {
System.out.println("Erase a Square.");
}
}
class Triangle implements Shape {
@Override
public void draw() {
System.out.println("Draw a Triangle.");
}
@Override
public void erase() {
System.out.println("Erase a Triangle.");
}
}
```
然后是 `NewShapes.java` 的代码:
```java
import java.util.Random;
public class NewShapes {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Square();
shapes[2] = new Triangle();
Random random = new Random();
for (int i = 0; i < 9; i++) {
int index = random.nextInt(3);
Shape shape = shapes[index];
shape.draw();
shape.erase();
System.out.println();
}
}
}
```
在 `NewShapes.java` 中,我们先创建了一个 `Shape` 数组,里面存放了三种不同的形状。然后使用 `Random` 类生成随机数来随机选择一种形状进行绘图和擦除操作,重复执行 9 次。最后输出一个空行,以便区分每次执行的结果。
阅读全文