使用Java定义Shape接口实现多态。 interface Shape{ void draw(); void erase(); } Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图。Circle类的定义示例: class Circle implements Shape{ public void draw(){ System.out.println("Calling Circle.draw()"); } public void erase(){ System.out.println("Calling Circle.erase ()"); } }
时间: 2024-01-06 22:03:26 浏览: 65
下面是实现题目要求的Java代码:
```
import java.util.Random;
interface Shape {
void draw();
void erase();
}
class Circle implements Shape {
public void draw() {
System.out.println("Calling Circle.draw()");
}
public void erase() {
System.out.println("Calling Circle.erase()");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Calling Square.draw()");
}
public void erase() {
System.out.println("Calling Square.erase()");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("Calling Triangle.draw()");
}
public void erase() {
System.out.println("Calling Triangle.erase()");
}
}
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 shapeType = random.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;
}
}
for (Shape shape : shapes) {
shape.draw();
shape.erase();
}
}
}
```
上面的代码定义了一个 `Shape` 接口,其中包含了 `draw()` 和 `erase()` 方法。接着,`Circle`、`Square`、`Triangle` 类分别实现了 `Shape` 接口,并且实现了 `draw()` 和 `erase()` 方法。最后,`NewShapes` 类利用 `Random` 类生成随机数来创建不同的图形对象,并且调用这些图形对象的 `draw()` 和 `erase()` 方法。通过这个例子,我们可以看到多态的用法,即在运行时根据对象的实际类型来选择调用哪个方法。
阅读全文