多态性分为静态联编,动态联编
静态联编:在程序编译时进行,具体为函数重载,比较好理解
动态联编:在程序运行是进行,具体为继承关系中,子类与父类同名函数,根据函数调用时参数具体指向的参数类型
用这个例子来理解动态联编
public class多态性{
public static void main(String [] args){
Animal a = new Animal();
animalShout(一);
Dogd =new Dog();
animalShout(d);
Cat c = new Cat();
animalShout(C);
Animal dog = new Dog(); //多态性是看具体对的具体属性,即变量指向具体的具体(向上自动转型)
animalShout(dog);
Dog dog_2 =(Dog)dog;(向下强制转型)
}
public static void animalShout(动物一){
a.shout();
}
}
public class Animal {
public void shout(){
System.out.println(“shouting ......”);
}
}
public class Dog extends Animal {
public void shout() {
System.out.println("汪汪汪 ……");
}
}
public class Cat extends Animal {
public void shout() {
System.out.println("喵喵喵 ……");
}
}