java多态实现电子宠物系统

本文实例为大家分享了java多态实现电子宠物系统的具体代码,供大家参考,具体内容如下
效果实现: java多态实现电子宠物系统
文章图片

代码实现: 1、主人类:

public class Master {//领养public Pet adopt(String name){if ("狗狗".equals(name)){return new Dog(); }else if (name.equals("企鹅")){return new Penguin(); }return null; }//喂食public void feed(Pet pet, String food){pet.eat(food); }//玩耍public void play(Pet pet){if(pet instanceof Dog){Dog d= (Dog) pet; d.catchDisk(); }else if(pet instanceof Penguin){Penguin p= (Penguin) pet; p.swimInSouth(); }}//捐献public Pet donate(String name){if("狗狗".equals(name)){return new Dog(); }else if(name.equals("企鹅")){return new Penguin(); }return null; }}

2、狗狗类:
public class Dog extends Pet {public void catchDisk(){System.out.println("狗狗接飞盘!"); }public Dog(int health) {super(health); }public Dog() {}@Overridepublic void eat(String food) {System.out.println("狗狗吃"+food+",吃饱后健康值+3"); setHealth(getHealth()+3); }}

3、企鹅类:
public class Penguin extends Pet{public void swimInSouth(){System.out.println("企鹅在南极游泳!"); }public Penguin(int health) {super(health); }public Penguin() {}@Overridepublic void eat(String food) {System.out.println("企鹅宝宝吃"+food+",吃完后,健康值加5"); setHealth(getHealth()+5); }}

4、宠物类,Pet:
public class Pet {private int health; public int getHealth() {return health; }public void setHealth(int health) {this.health = health; if(this.health>100){this.health=100; System.out.println("已经吃饱了,再吃就撑破了"); }}public Pet() {}public Pet(int health) {this.health = health; }public void eat(String food){System.out.println("宠物吃"+food); }}

5、测试类:
public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in); Master master = new Master(); //领养System.out.print("请输入您要领养的宠物:"); String dname = sc.next(); Pet p = master.adopt(dname); //主人给狗狗喂食,玩耍System.out.print("请输入您要喂得食物:"); String dfood = sc.next(); master.feed(p,dfood); System.out.println(p.getHealth()); master.play(p); //主人给企鹅喂食,玩耍System.out.print("请输入您要玩的宠物:"); String pname = sc.next(); p = master.adopt(pname); System.out.print("请输入您要喂的食物:"); String pfood = sc.next(); master.feed(p,pfood); System.out.println(p.getHealth()); master.play(p); //捐赠出去System.out.print("请输入您要捐赠的宠物:"); String jname = sc.next(); Pet pet = master.donate(jname); System.out.println(); System.out.println("您捐献的是:"+pet.getClass().getName()); }}

补:这里测试类我是让用户在控制台输入,如果不想输入,可将测试类Test换成下面的代码:
public class TestPet {public static void main(String[] args) {Master m = new Master(); //领养Pet p = m.adopt("狗狗"); //主人给狗狗喂食,玩耍m.feed(p,"大骨头"); System.out.println(p.getHealth()); m.play(p); //主人给企鹅喂食,玩耍p = m.adopt("企鹅"); m.feed(p,"小鱼"); System.out.println(p.getHealth()); m.play(p); //捐献出去Pet pet = m.donate("狗狗"); System.out.println("您捐献的是:"+pet.getClass().getName()); }}

【java多态实现电子宠物系统】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读