特殊的switch用法
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)){
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();
}
}
}
}
在上面的代码中会出现错误.编译器报错如下:
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
此方法必须返回 Shape 类型的结果
at RandomShapeGenerator.next(Duotai.java:88)
at Duotai.main(Duotai.java:102)
其实因为编译器不可能完全智能判断你的switch语句已经包含所有情况了.
所以要么在switch中加个default分支,要么在switch之外加个return null;
解决方案1:加一个defaule分支.
class RandomShapeGenerator{
private Random random = new Random();
public Shape next(){
switch(random.nextInt(3)){
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
default:return new Shape();//添加了一个分支.
}
}
}
解决方案2: 在switch之外加个Shape s = null;
class RandomShapeGenerator{
private Random random = new Random();
public Shape next(){
Shape s = null;
switch(random.nextInt(3)){
case 0:return s = new Circle();
case 1:return s = new Square();
case 2:return s = new Triangle();
}
return s;
}
}