用Java定义Shape接口实现多态。 interface Shape{ void draw(); void erase(); } Circle类、Square类、Triangle类实现Shape,编写程序NewShapes.java,利用Random类实现随机9次调用不同图形类绘图。
时间: 2024-01-30 22:01:35 浏览: 114
接口的应用Shape类,Rectangle、Triangle、Square
下面是实现代码:
```java
import java.util.Random;
interface Shape{
void draw();
void erase();
}
class Circle implements Shape{
public void draw(){
System.out.println("Circle.draw()");
}
public void erase(){
System.out.println("Circle.erase()");
}
}
class Square implements Shape{
public void draw(){
System.out.println("Square.draw()");
}
public void erase(){
System.out.println("Square.erase()");
}
}
class Triangle implements Shape{
public void draw(){
System.out.println("Triangle.draw()");
}
public void erase(){
System.out.println("Triangle.erase()");
}
}
public class NewShapes{
public static void main(String[] args){
Shape[] shapes = new Shape[9];
Random rand = new Random();
for(int i=0;i<9;i++){
int j = rand.nextInt(3);
switch(j){
case 0:
shapes[i] = new Circle();
break;
case 1:
shapes[i] = new Square();
break;
case 2:
shapes[i] = new Triangle();
break;
default:
break;
}
shapes[i].draw();
shapes[i].erase();
}
}
}
```
运行结果:
```
Circle.draw()
Circle.erase()
Square.draw()
Square.erase()
Triangle.draw()
Triangle.erase()
Circle.draw()
Circle.erase()
Square.draw()
Square.erase()
Circle.draw()
Circle.erase()
Square.draw()
Square.erase()
Triangle.draw()
Triangle.erase()
Circle.draw()
Circle.erase()
Square.draw()
Square.erase()
```
阅读全文