面向对象中级-继承(动物喂食案列)
用继承的方式写出一个主人不给不同的动物喂不同食物的一个案列
主类 Poly01
package com.hspedu.poly_;
public class Poly01 {
public static void main(String[] args) {
Master master = new Master("汤姆");
Dog dog = new Dog("大黄");
Bone bone = new Bone("大骨棒");
Cat cat = new Cat("小花猫");
Fish fish = new Fish("黄花鱼");
master.feed(dog,bone);
master.feed(cat,fish);
}
}
主人-Master
package com.hspedu.poly_;
public class Master {
private String name;
public Master(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//完成主人给狗喂食骨头的方法
public void feed(Dog dog,Bone bone){
System.out.println("主人" + name + "给" + dog.getName() + "吃" + bone.getName());
}
//完成主人给猫喂食鱼的方法
public void feed(Cat cat,Fish fish){
System.out.println("主人" + name + "给" + cat.getName() + "吃" + fish.getName());
}
}
父类-动物 Animal
package com.hspedu.poly_;
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
父类-食物 Food
package com.hspedu.poly_;
public class Food {
private String name;
public Food(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
子类-动物-Dog
package com.hspedu.poly_;
public class Dog extends Animal{
public Dog(String name){
super(name);
}
}
子类-动物-Fish
package com.hspedu.poly_;
public class Fish extends Food{
public Fish(String name) {
super(name);
}
}
子类-动物-Cat
package com.hspedu.poly_;
public class Cat extends Animal{
private String name;
public Cat(String name) {
super(name);
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
子类-食物-Bone
package com.hspedu.poly_;
public class Bone extends Food{
public Bone(String name) {
super(name);
}
}
子类-食物-Fish
package com.hspedu.poly_;
public class Fish extends Food{
public Fish(String name) {
super(name);
}
}
运行结果