package 多态.典型用法;/** 宠物 父类* */public abstract class Pet { private int health;//健康 public int getHealth() { return health; } public void setHealth(int health) { this.health = health; } //宠儿生病去医院 public abstract void toHopsoital(); public abstract void eat();}
package 多态.典型用法;/** 狗类* */public class Dog extends Pet { @Override public void toHopsoital() { System.out.println("打针"); System.out.println("吃药"); //狗的治疗健康度+3 int old = this.getHealth(); this.setHealth(old+3); } public void jiefeipan(){ System.out.println("接飞盘"); } @Override public void eat() { System.out.println("狗吃屎"); int old = this.getHealth(); this.setHealth(old+30); }}
package 多态.典型用法;/** 企鹅* */public class Penguin extends Pet { @Override public void toHopsoital() {// System.out.println("打针"); System.out.println("吃药"); //企鹅的治疗健康度+5 int old = this.getHealth(); this.setHealth(old+5); } public void qianshui(){ System.out.println("潜水"); } @Override public void eat() { System.out.println("企鹅吃毛线"); int old = this.getHealth(); this.setHealth(old+50); }}
package 多态.典型用法;/** snake类* */public class Snake extends Pet { @Override public void toHopsoital() { System.out.println("打针"); System.out.println("吃药"); //狗的治疗健康度+3 int old = this.getHealth(); this.setHealth(old+6); } @Override public void eat() { System.out.println("你就啥都吃不到" ); int old = this.getHealth(); this.setHealth(old+60); }}
package 多态.典型用法;/* *对象 instanceof 类或接口 * 判断对象是否是该类的对象,如果是返回true,不是返回false * * */public class Master { // void cure(Pet pet) { //赋值是父类 传参传的类型是子类对象 相当于Pet pet=dog Pet是父类 dog是子类 pet.toHopsoital(); //想调用子类独有的方法 //如果传进来的类型 if (pet instanceof Dog) { ((Dog) pet).jiefeipan(); } else if (pet instanceof Penguin) { ((Penguin) pet).qianshui(); } } void eat(Pet pet){ pet.eat(); }}
package 多态.典型用法;/** 不用多态 增加一种宠物类** */public class Test { public static void main(String[] args) { Master master = new Master();// Dog dog =new Dog(); dog.setHealth(22); master.cure(dog); // Pet pet=dog System.out.println("治疗后健康度是"+dog.getHealth()); Penguin penguin =new Penguin(); penguin.setHealth(19); master.cure(penguin); System.out.println("治疗后健康度是"+penguin.getHealth()); Snake snake =new Snake(); snake.setHealth(19); master.cure(snake); System.out.println("治疗后健康度是"+snake.getHealth()); master.eat(dog); System.out.println("健康度是"+dog.getHealth()); master.eat(penguin); System.out.println("健康度是"+penguin.getHealth()); master.eat(snake); System.out.println("健康度是"+snake.getHealth()); } }