package Ex01; import java.util.Scanner; /** * @Author:Adminstrator * @Date:2021-11-03 * @Description:使用多态实现为宠物喂食 和 使用多态实现主人领养宠物并与宠物玩耍功能 * 需求说明1、宠物饿了,主人需要为宠物喂食,使用多态实现该过程不同宠物吃的东西不一样, * 不同宠物吃完东西后恢复健康值不一样健康值达到100时,不需要继续喂食 * 需求说明2、狗具有特有的接飞盘方法,企鹅具有特有的南极游泳方法。 * 请编写测试类分别调用各种具体宠物的特有方法;使用向下转型,使用instanceof判断宠物类型 */ public class Pet { String name; int health; @Override public String toString() { //重写的toString()方法 return name +"health="+ health; } void eat() { } } class Dog extends Pet { public Dog() { this.name = "狗狗"; this.health = 80; } void skill(){ //狗狗特有技能 System.out.println("我是狗狗,我可以接飞盘!"); } void eat() { this.health += 3; if (this.health >= 100) { this.health = 100; } } } class Penguin extends Pet { public Penguin() { this.name = "企鹅"; this.health = 80; } void skill(){ //企鹅特有技能 System.out.println("我是企鹅,我可以在南极游泳!"); } void eat() { this.health += 5; if (this.health >= 100) { this.health = 100; } } } class Master { void giveFood(Pet a) { a.eat(); } public static void main(String[] args) { Master m = new Master(); Pet d = new Dog();//向上转型 Pet p = new Penguin();//向上转型 if(d instanceof Dog)//用于判断d是否是Dog的实例 ((Dog) d).skill() ;//向下转型,执行Dog的特有技能 if(p instanceof Penguin)//用于判断p是否是Penguin的实例 ((Penguin) p).skill();//向下转型,执行penguin的特有技能 m.giveFood(d);//主人给d喂食 m.giveFood(p);//主人给p喂食 System.out.println(d.toString()); System.out.println(p.toString()); } }
package Ex01; import java.util.Scanner; /** * @Author:Adminstrator * @Date:2021-11-03 * @Description:打印商品价格 * 需求说明:自定义类和方法,使用父类作为返回值实现打印不同类型商品价格功能 * 父类:Goods(商品类) * 子类:TVs(电视类)、Foods(食品类) */ public class Human { public void printGoods(Goods s){ System.out.println(s.name+"的价格为:"+s.price); } public static void main(String[] args) { Goods a=new TVs("电视机",5000); Goods b=new Foods("奶粉",200); Human h=new Human(); h.printGoods(a); h.printGoods(b); } } class Goods { String name; double price; } class TVs extends Goods{ public TVs( String a, double b) { this.name=a; this.price=b; } } class Foods extends Goods{ public Foods(String a, double b) { this.name=a; this.price=b; } }