* - Shape基类 拥有draw()和erase()两个方法
* - 基于Shape类创建Circle子类
* - 基于Shape类创建Square子类
* - 创建Shape类创建Triangle子类
* - 创建随机形状发生的类(不是子类)
* - 定义公共类(测试类),创建Shape类的数组对象长度为10,并为对象数组赋值其内容Circle,Square,Triangle子类对象
public class Shape {public void draw() {System.out.println("正在绘制图形...");}public void erase() {System.out.println("正在擦除图形...");}
}
/*** Circle子类*/
public class Circle extends Shape {//重写父类的draw方法//crtl+o 可以快速重写父类方法@Overridepublic void draw() {System.out.print("⚫");}
}
/*** Square子类*/
public class Square extends Shape {@Overridepublic void draw() {System.out.print("◼");}
}
/*** Triangle子类*/
public class Triangle extends Shape {@Overridepublic void draw() {System.out.print("▲");}
}
/*** 随机类*/
public class Random{public Shape randomShape(){int randomNum = (int)(Math.random()*3);if (randomNum == 0){return new Circle();}else if (randomNum == 1){return new Square();}else{return new Triangle();}}
}
/*** 定义公共类(测试类),创建Shape类的数组对象长度为10* 并为对象数组赋值其内容Circle,Square,Triangle子类对象*/public class TestShape {public static void main(String[] args) {Shape[] shape = new Shape[10];Random ran = new Random();//汇总所有的子类对象到数组中for(int i=0;i<shape.length;i++){//随机方法shape[i] = ran.randomShape();}//呈现方式for(int i=0;i< shape.length;i++){shape[i].draw();}}
}