//加入现在需要创建三个猫对象和三个狗对象并使用eat方法,如果我们按照正常的思路:
class Demo_Animal{
public static void main(String[] args) {
Cat c1=new Cat();
Cat c2=new Cat();
Cat c3=new Cat();
Dog d1=new Dog();
Dog d2=new Dog();
Dog d3=new Dog();
c1.eat();
c2.eat();
c3.eat();
d1.eat();
d2.eat();
d3.eat();
}
}
//显然这样写代码冗余,我们可以先优化一下创建对象和调用方法的过程,把创建对象和调用方法的过程提取成为一个方法
class Demo_Animal{
public static void main(String[] args) {
method(Cat c1);
method(Cat c2);
method(Cat c3);
method(Dog d1);
method(Dog d2);
method(Dog d3);
}
public static void method(Cat c){
c.eat();
}
public static void method(Dog d){
d.eat();
}
}
//这个时候,如果有十个,百个类,猫,狗,猪,牛,羊........我们每次都需要写一个对应的method,这样是不现实的,因
//此我们需要进一步优化,使用多态,把父类当做形参
class Demo_Animal{
public static void main(String[] args) {
method(Cat c1);
method(Cat c2);
method(Cat c3);
method(Dog d1);
method(Dog d2);
method(Dog d3);
}
public static void method(Animal a){
a.eat();
}
}