继承父类,子类含有两个分别为boy、Girl类名。
返回是需要返回方法

则返回变量名Person

class Person {
void eat() {}
void speak() {}
}
class Boy extends Person {
void eat() {
System.out.println("Boy.eat()");
}
void speak() {
System.out.println("Boy.speak()");
}
}
class Girl extends Person {
void eat() {
System.out.println("Girl.eat()");
}
void speak() {
System.out.println("Girl.speak()");
}
}
public class Persons {
public static Person randPerson(){
try{
switch ((int)(Math.random() * 2))//随机数
{
default:
case 0:
return new Boy();
case 1:
return new Girl();
}
}catch(Exception e){
System.out.print("异常情况为"+e);
}
return new Person();
}
public static void main(String[] args) {
Person[] p = new Person[4];
for (int i = 0; i < p.length; i++) {
p[i] = randPerson(); // 随机生成Boy或Girl
}
for (int i = 0; i < p.length; i++) {
p[i].eat();
}
}
}
跳出循环return,也是能跳出循环
switch ((int)(Math.random() * 2))//随机数
{
default:
case 0:
new Boy();
break;
case 1:
new Girl();
break;
}