多态 也称为后期绑定 (late binding),只要不是后期绑定就不是多态!
所谓绑定 就是建立method call(函数调用)和method body(函数本体)的关联。绑定分为先期绑定和后期绑定,发生在程序执行之前的是先期绑定,过程式语言一定是先期绑定的;绑定动作在执行期才根据对象型别进行的是后期绑定 。Java中的所有函数除了被声明为final和satatic外,皆为后期绑定,而且都是会自动发生的,可以这么理解“发送消息给某个对象,让该对象自行找到应该做的事就好了”。
显然可以推出成员变量和静态函数是不具有多态性的,因为它们在编译时绑定的。
说到多态我们不得不说两个概念 向上转型 (upcasting)和向下转型 (downcasting)
举个很简单的例子去理解多态 向上转型 向下转型
多 态 : 猫科动物有老虎 、狮子、猫等等
向上转型 : 老虎有猫科动物共有的特征(子类一定能转成父类类型)
向下转型 : 猫科动物不一定有老虎的本领(父类不一定能转成子类类型,有可能抛出异常)
package Polymorphism;
class Tiger extends Catamount {
void wow() {
System.out.println("Tiger WOW");
};
void forestLife() {
System.out.println("Tiger is the king of the forest!");
};
};
class Lion extends Catamount {
void wow() {
System.out.println("Lion WOW");
};
void glasslandLife() {
System.out.println("Lion is the king of grassland!");
};
};
class Cat extends Catamount {
void wow() {
System.out.println("Cat WOW");
};
void domesticate() {
System.out.println("Cats is a human pet!");
};
};
public class Catamount {
void wow() {
System.out.println("Catamount will be called!");
}
public static void main(String[] args) {
Catamount c[] = { new Catamount(), new Tiger(), new Lion(), new Cat() };
c[1].wow();// upcasting
c[2].wow();// upcasting
c[3].wow();// upcasting
((Tiger) c[1]).forestLife();// downcasting
// ((Tiger) c[0]).forestLife();// Exception thrown 屏蔽了!
((Lion) c[2]).glasslandLife();// downcasting
((Cat) c[3]).domesticate();// downcasting
}
}
Tiger WOW Lion WOW Cat WOW Tiger is the king of the forest! Lion is the king of grassland! Cats is a human pet!
注:Java里的每个转型动作都会被检查,所以即使看起来不过是圆括号表示的一般转型动作,执行时期却会加以检查以确保它的确是你所认知的型别,如果转型不成功,你便会受到ClassCastException,这一动作被称为“执行期型别辨别(run-time type identification,RTTI)。