1.什么是多态
Dog dog1 = new Dog();
Animal dog2 =new Dog(); //Dog对象也可以赋值给父类型变量来表示
2.多态的特点
1.多态形式的特点展现是对重写方法,因为在编译时是找当前变量类是否有这个方法。上图Animal类型的变量去调用eat(),如果Animal中没有eat()编译不会通过会报错。编译通过之后,运行时就直接先在对象本身类Dog中去找找不到再到父类
2.字段没有多态形式,变量是什么类型就找到那个类的字段
3.静态也没有因为在还没有开始执行就加载到了方法区,直接就是变量的类来调用
3.多态的好处
pulic class Person{
void feedDog(Dog dog){
dog.eat();
}
void feedCat(Cat cat){
cat.eat();
}
public static void main(String[] args){
Person per = new Person();
Dog dog = new Dog();
per.feedDog(dog);
Cat cat = new Cat();
per.feedCat(cat);
}
}
public class Person{
void feedAnimal(Animal anim){
anim.eat();
}
public static void main(String[] args){
Person per = new Person();
Animal dog - new Dog();
Animal cat = new Cat();
per.feedAnimal(cat);
}
}