Java在异常抛出怎么返回类名

继承父类,子类含有两个分别为boy、Girl类名。

返回是需要返回方法

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 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();
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/BI-LI/p/9269557.html