实现主人领养宠物并带宠物去玩,狗狗叼飞碟,企鹅去南极游泳
生活随笔
收集整理的這篇文章主要介紹了
实现主人领养宠物并带宠物去玩,狗狗叼飞碟,企鹅去南极游泳
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
main方法程序代碼:
package com.bdqn;public class PetTest {public static void main(String[] args) {Master master = new Master();Pet dog = new Dog();dog.setName("黑鼻");dog.setHealth(88);dog.setLove(78);((Dog) dog).setStrain(1);dog.print();dog.play();System.out.println("**********************");Pet penguin = new Penguin();penguin.setName("QQ");penguin.setHealth(77);penguin.setLove(76);((Penguin) penguin).setSex(1);penguin.print();penguin.play();} }主人類代碼:
package com.bdqn;public class Master {public void playWithPet(Pet pet){if(pet instanceof Dog){Dog dog = (Dog)pet;dog.play();}else if(pet instanceof Penguin){Penguin penguin = (Penguin) pet;penguin.play();}} }Pet類代碼:
package com.bdqn;public abstract class Pet {private String name;private int health;private int love;public void setName(String name) {this.name = name;}public String getName() {return name;}public void setHealth(int health) {if(health < 0 || health > 100){health = 60;}this.health = health;}public int getHealth() {return health;}public void setLove(int love) {if(love < 0 || love > 100){love = 60;}this.love = love;}public int getLove() {return love;}public void print(){System.out.println("寵物的自白:");System.out.print("我的名字叫"+getName()+",健康值是"+getHealth()+",和主人的親密度是"+getLove());}public abstract void play(); }Dog類代碼:
package com.bdqn;public class Dog extends Pet{private String strain;public String getStrain() {return strain;}public void setStrain(int strain) {if(strain == 1){this.strain = "拉布拉多";return;}this.strain = "博美";}public void print(){super.print();System.out.println(",我的種類是:"+this.getStrain());}public void play() {System.out.println("扔飛碟出去,狗狗跑去撿回來......");}public void toHospital(){System.out.println("打針、吃藥");super.setHealth(60);} }Penguin類代碼:
package com.bdqn;public class Penguin extends Pet{private String sex;public String getSex() {return sex;}public void setSex(int sex) {if(sex == 1 ){this.sex = "Q仔";return;}this.sex = "Q妹";}public void print(){super.print();System.out.println(",我的性別是:"+this.getSex());}public void play() {System.out.println("帶企鵝去南極游泳......");} }程序運行結果:
?
轉載于:https://www.cnblogs.com/yangwenxiang/p/10299573.html
總結
以上是生活随笔為你收集整理的实现主人领养宠物并带宠物去玩,狗狗叼飞碟,企鹅去南极游泳的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高德地图巡航异步加载数据_python3
- 下一篇: 静态类型的 NSUserDefaults