日期:2014-05-20  浏览次数:20764 次

此方法必须返回 Shape 类型的结果?
import   java.util.Random;
class   Shape{
void   draw(){}
void   erase(){}
}

class   Circle   extends   Shape{
void   draw(){
System.out.println( "Circle.draw() ");
}
void   erase(){
System.out.println( "Circle.erase ");
}
}

class   Square   extends   Shape{
void   draw(){
System.out.println( "Square.draw() ");
}
void   erase(){
System.out.println( "Square.erase ");
}
}

class   Triangle   extends   Shape{
void   draw(){
System.out.println( "Triangle.draw() ");
}
void   erase(){
System.out.println( "Triangle.erase ");
}
}

class   RandomShapeGenerator{
private   Random   random   =   new   Random();
public   Shape   next(){ //error, 此方法必须返回   Shape   类型的结果
switch(random.nextInt(3)){
//default:
case   0:return   new   Circle();
case   1:return   new   Square();
case   2:return   new   Triangle();
}
}
}
public   class   Duotai{
private   static   RandomShapeGenerator   gen   =   new   RandomShapeGenerator();
public   static   void   main(String[]   args){
Shape[]   s   =   new   Shape[4];
for(   int   i   =   0;   i <   s.length;   i++   ){
s[i]   =   gen.next();
for(   int   j   =   0;   j <   s.length;   j++   ){
s[j].draw();
}
}
}
}

------解决方案--------------------
实际返回的类型都是Shape 的子类


------解决方案--------------------
error?
------解决方案--------------------
public Shape next(){ //error, 此方法必须返回 Shape 类型的结果
switch(random.nextInt(3)){
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
default: return new Shape();
}