复制代码
- //:Shapes.java
- //PolymorphisminJava
- classShape{
- voiddraw(){}
- voiderase(){}
- }
- classCircleextendsShape{
- voiddraw(){
- System.out.println("Circle.draw()");
- }
- voiderase(){
- System.out.println("Circle.erase()");
- }
- }
- classSquareextendsShape{
- voiddraw(){
- System.out.println("Square.draw()");
- }
- voiderase(){
- System.out.println("Square.erase()");
- }
- }
- classTriangleextendsShape{
- voiddraw(){
- System.out.println("Triangle.draw()");
- }
- voiderase(){
- System.out.println("Triangle.erase()");
- }
- }
- publicclassShapes{
- publicstaticShaperandShape(){
- switch((int)(Math.random()*3)){
- default://Toquietthecompiler
- case0:returnnewCircle();
- case1:returnnewSquare();
- case2:returnnewTriangle();
- }
- }
- publicstaticvoidmain(String[]args){
- Shape[]s=newShape[9];
- //Fillupthearraywithshapes:
- for(inti=0;i<s.length;i++)
- s[i]=randShape();
- //Makepolymorphicmethodcalls:
- for(inti=0;i<s.length;i++)
- s[i].draw();
- }
- }///:~
复制代码
- Circle.draw()
- Triangle.draw()
- Circle.draw()
- Circle.draw()
- Circle.draw()
- Square.draw()
- Triangle.draw()
- Square.draw()
- Square.draw()
欢迎光临 仓酷云 (http://ckuyun.com/) | Powered by Discuz! X3.2 |