标签:class equal 宠物 返回 stat cat sys out 类型
宠物类
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(); } }
结果
标签:class equal 宠物 返回 stat cat sys out 类型
原文地址:https://www.cnblogs.com/lev1/p/11217883.html