今天小编给大家分享一下怎么用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()); } }
以上就是“怎么用java多态实现电子宠物系统”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。