Animal()动物类,关于多态的练习
仅做自己练习总结
1.Dog和Cat两个类都有eat();表现形式猫了饭后喵喵叫,狗吃了饭后汪汪叫,模拟人喂食的这个过程;
2.多了一个动物叫鸭子,然后也要人去喂;
问题:如果再领养XXX宠物,就需要给XXX喂食,怎么办?
思路:
这样频繁修改代码,代码可扩展性、可维护性差。使用多态优化。
1.添加Animal类,增加eat方法,让Dog,Cat,Duck继承Animal;
2.重写eat方法修改feet的方法
Animal
/**
* @author Linm
* @title
* @date 2021/8/16 17:43
*/
public class Animal {
public String name;
public Animal() {
}
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println();
}
}
Cat
/**
* @author Linm
* @title
* @date 2021/8/16 17:23
*/
public class Cat extends Animal{
public Cat(String name){
super(name);
}
@Override
public void eat() {
System.out.println(this.name+"吃了鱼喵喵叫");
}
}
Dog
/**
* @author Linm
* @title
* @date 2021/8/16 17:27
*/
public class Dog extends Animal{
public Dog(String name){
super(name);
}
@Override
public void eat(){
System.out.println(this.name+"吃骨头汪汪叫");
}
}
Duck
/**
* @author Linm
* @title
* @date 2021/8/17 10:22
*/
public class Duck extends Animal {
public Duck(String name){
super(name);
}
@Override
public void eat(){
System.out.println(this.name+"吃了米嘎嘎叫");
}
}
Person
/**
* @author Linm
* @title
* @date 2021/8/16 17:04
*/
public class Person {
String name;
Person(){
}
Person(String name){
this.name = name;
}
public void feed(Animal animal){
System.out.print(this.name+"喂了"+animal.name+",");
animal.eat();
}
}
测试:
/**
* @author Linm
* @title
* @date 2021/8/16 17:29
*/
public class Demo03 {
public static void main(String[] args) {
Animal cat =new Cat("cat");
Animal dog = new Dog("dog");
Animal duck = new Duck("duck");
Person person = new Person("李雷");
person.feed(cat);
person.feed(dog);
person.feed(duck);
}
}
输出结果:
李雷喂了cat,cat吃了鱼喵喵叫
李雷喂了dog,dog吃骨头汪汪叫
李雷喂了duck,duck吃了米嘎嘎叫
Process finished with exit code 0