时间:2022-12-15 10:31:56 | 栏目: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() { } @Override public 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() { } @Override public 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()); } }