日期:2014-05-20 浏览次数:20944 次
import java.util.*;
class No{
void thePri(){
System.out.println("NO");
}
}
class No1 extends No{
void thePri(){
System.out.println("NO1");
}
}
class No2 extends No{
void thePri(){
System.out.println("NO2");
}
}
class No3 extends No{
void thePri(){
System.out.println("NO3");
}
}
/*
疑问就在下面的代码中
问题一:去掉default后程序提示错误!这里有我设定3个随机数,分别已经对应了,为什么没有default不能运行?
问题二:当我建立RandomNo对象时,并调用sel()方法,返回值是No,方法里面的switch 语句并没有break语句,比如得到的随机数
是1,那么就是执行return new No2(),而后面没有break,程序理应当会继续执行接下来的return new No3(),也就是说
每次调用这个方法时,只会返回new No3(),不会分别返回相应的内容。
但是结果不是这样的,而是会自行返回相应的内容?这是为什么???
*/
class RandomNo{
private Random rand = new Random();
private int i = rand.nextInt(3);
public No sel(){
switch(i){
default:
case 0:return new No1();
case 1:return new No2();
case 2:return new No3();
}
}
}
public class Demo1{
public static void main(String[] args){
RandomNo del = new RandomNo();
No a = new No();
a = del.sel();
a.thePri();
}
}
import java.util.*;
/*
这里就可以去掉default,假设i 得到的随机数字是0,就会执行System.out.println("1"),因为后面没有break
就继续执行System.out.println("2");System.out.println("3");结果就是:
1
2
3
为什么这里遵守switch的原则,而上面则不是??
*/
class RandomPro{
private Random rand = new Random();
private int i = rand.nextInt(3);
public void ret(){
switch(i){
//default:
case 0:System.out.println("1");
case 1:System.out.println("2");
case 2:System.out.println("3");
}
}
}
public class Demo2{
public static void main(String[] args){
RandomPro a = new RandomPro();
a.ret();
}
}