5)定义Shape接口实现多态。 interface Shape{ void draw(); void erase(); } Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图。并涉及到的知识Java
时间: 2024-02-03 08:12:15 浏览: 66
接口的应用Shape类,Rectangle、Triangle、Square
下面是Shape接口和各个图形类的定义:
```java
interface Shape {
void draw();
void erase();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public void erase() {
System.out.println("Erasing a circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
@Override
public void erase() {
System.out.println("Erasing a square");
}
}
class Triangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a triangle");
}
@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}
```
然后可以编写一个NewShapes类,利用Random类随机生成数字,根据数字生成不同的图形并调用相应的方法:
```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);
shapes[index].draw();
shapes[index].erase();
System.out.println();
}
}
}
```
这里创建了一个包含三种图形的数组,并用Random类随机生成索引,然后调用相应的方法。在我的实现中,每次循环输出一对draw和erase操作的结果,中间用一个空行隔开。
阅读全文