Java定义Shape接口实现多态。 interface Shape{ void draw(); void erase(); } Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图。 定义Shape接口实现多态。 interface Shape{ void draw(); void erase(); } Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图。
时间: 2024-01-29 18:04:20 浏览: 68
下面是实现要求的代码:
```java
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) {
Shape[] shapes = new Shape[9];
Random rand = new Random();
for (int i = 0; i < shapes.length; i++) {
int randNum = rand.nextInt(3);
if (randNum == 0) {
shapes[i] = new Circle();
} else if (randNum == 1) {
shapes[i] = new Square();
} else {
shapes[i] = new Triangle();
}
}
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw();
shapes[i].erase();
System.out.println();
}
}
}
```
程序首先定义了一个Shape接口,其中包含draw()和erase()两个方法。然后Circle、Square、Triangle三个类分别实现了Shape接口,并实现了接口中的两个方法。最后NewShapes类利用Random类随机生成9个不同的Shape对象,然后依次调用每个对象的draw()和erase()方法。
程序的输出结果类似于下面这样:
```
Drawing a triangle
Erasing a triangle
Drawing a circle
Erasing a circle
Drawing a square
Erasing a square
Drawing a triangle
Erasing a triangle
Drawing a square
Erasing a square
Drawing a circle
Erasing a circle
Drawing a square
Erasing a square
Drawing a square
Erasing a square
Drawing a triangle
Erasing a triangle
```
可以看到,程序随机生成了三种形状的对象,并依次调用它们的draw()和erase()方法。这就是Java中多态的一种体现。
阅读全文