Lev1

导航

补充上次的将父类作为方法的返回类型

宠物类

package cn.Animal;

public class Animal {
    public void play() {}
}

狗类

package cn.Animal;

public class Dog extends Animal {
    public void play() {
        System.out.println("狗在玩蛇");
    }
}

猫类

package cn.Animal;

public class Cat extends Animal {
    public void play() {
        System.out.println("猫咪在玩球");
    }
}

鸭子类

package cn.Animal;

public class Duck extends Animal {
    public void play() {
        System.out.println("鸭子在玩水");
    }
}

主人类

package cn.Animal;
//主人类
public class Host {
    //动物在玩不同的游戏,将父类作为方法的返回类型
    public Animal toPlay(String type) {
        Animal animal = null;
        if(type.equals("cat")) {
            animal =  new Cat();
        }else if(type.equals("dog")) {
            animal = new Dog();
        }else {
            animal =  new Duck();
        }
        return animal;
    }
    
}

测试类

package cn.Animal;

public class Test {
        public static void main(String[] args) {
            Host host = new Host();
            Animal animal = host.toPlay("dog");
            animal.play();
        }
}

结果

 

posted on 2019-07-20 15:27  Lev1  阅读(160)  评论(0编辑  收藏  举报