子类方法对父类方法的覆盖以及一般方法的重载都可以看作是多态。
动态绑定是一种机制。引用变量的声明类型决定了编译时哪个方法匹配;编译时,编译器根据参数类型、参数个数和参数顺序匹配方法。一个方法可能在几个子类中实现,JAVA虚拟机在运行时动态绑定方法的实现,由变量引用的对象的实际类决定。
动态绑定的工作机制如下:假设对象o是类c1,c2.......cn的实例,其中c1是c2的子类,c2是c3的子类......cn-1是cn的子类,也就是说cn是最一般的类,c1是最特殊的类。如果对象o调用一个方法p,JAVA虚拟机依此在类c1,c2.......cn中找方法P的第一个实现。
package com.mypackage.extend;
public class Animal {
String type;
String name;
int age;
int weight;
void eat()
{
System.out.println("动物爱吃饭");
}
void breath()
{
System.out.println("动物呼吸");
}
void sleep(){
System.out.println("动物睡觉");
}
}
class Tiger extends Animal
{
String tigerType;
String from;
@Override
void breath() {
// TODO Auto-generated method stub
//super.breath();
System.out.println("老虎用肺呼吸");
}
void tigerRun()
{
System.out.println("老虎在奔跑");
}
}
不能通过数组来直接访问Tiger类自己的方法,必须要进行类型强制转换。因为动态绑定只对子类覆盖父类的方法有效,其他一般方法调用由声明的类型决定。使用A instanceof B用来判断A是否是B的一个实例,防止ClassCastException出现。
public class TestAnimal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal[] animal = new Animal[2];
animal[0] = new Animal();
animal[1] = new Tiger();
animal[0].breath();
animal[1].breath();
if(animal[1] instanceof Tiger)
((Tiger)animal[1]).tigerRun();
}
}