用java定义Shape接口实现多态。 interface Shapef void draw0; void erase@; Circle类、Square类、Triangle类实现Shape 编写程序NewShapes.java,利用Random 类实现随机9次调用不同图形类绘图。
时间: 2024-05-01 22:19:43 浏览: 101
好的,下面是代码实现:
Shape.java
```
public interface Shape {
void draw();
void erase();
}
```
Circle.java
```
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("绘制圆形");
}
@Override
public void erase() {
System.out.println("擦除圆形");
}
}
```
Square.java
```
public class Square implements Shape {
@Override
public void draw() {
System.out.println("绘制正方形");
}
@Override
public void erase() {
System.out.println("擦除正方形");
}
}
```
Triangle.java
```
public class Triangle implements Shape {
@Override
public void draw() {
System.out.println("绘制三角形");
}
@Override
public void erase() {
System.out.println("擦除三角形");
}
}
```
NewShapes.java
```
import java.util.Random;
public class NewShapes {
public static void main(String[] args) {
Shape[] shapes = new Shape[9];
Random random = new Random();
for (int i = 0; i < shapes.length; i++) {
int type = random.nextInt(3);
switch (type) {
case 0:
shapes[i] = new Circle();
break;
case 1:
shapes[i] = new Square();
break;
case 2:
shapes[i] = new Triangle();
break;
}
}
for (Shape shape : shapes) {
shape.draw();
shape.erase();
}
}
}
```
运行结果:
```
绘制正方形
擦除正方形
绘制三角形
擦除三角形
绘制圆形
擦除圆形
绘制正方形
擦除正方形
绘制圆形
擦除圆形
绘制正方形
擦除正方形
绘制三角形
擦除三角形
绘制三角形
擦除三角形
绘制圆形
擦除圆形
```
阅读全文