动态绑定是指在运行时解决方法调用与方法实现之间链接的过程(或者是在运行时调用被重写的方法的过程)。动态绑定也被称为运行时多态性或晚期绑定。动态绑定使用对象类型来解决绑定。
动态绑定的特点
Java 动态绑定示例
在这个例子中,我们创建了两个类 Animal 和 Dog,其中 Dog 类扩展了 Animal 类。在 main() 方法中,我们使用 Animal 类的引用,并赋给它一个 Dog 类的对象来测试动态绑定的效果。
package com.tutorialspoint;
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class Tester {
public static void main(String args[]) {
Animal a = new Animal();
Animal b = new Dog();
a.move();
b.move();
}
}
输出:
Animals can move
Dogs can walk and run
在上面的例子中,可以看到即使 b 是 Animal 类型,它还是运行了 Dog 类中的 move 方法。原因是:在编译时,检查的是引用类型。然而,在运行时,JVM 会识别出对象类型,并运行属于该特定对象的方法。
因此,在上面的例子中,由于 Animal 类有 move 方法,所以程序会正确编译。然后,在运行时,它会运行适用于该对象的方法。
使用 super 关键字的 Java 动态绑定
当调用超类版本的被重写方法时,使用 super 关键字,这样就可以在使用动态绑定的同时利用父类的方法。
示例:使用 super 关键字
在这个例子中,我们创建了两个类 Animal 和 Dog,其中 Dog 类扩展了 Animal 类。Dog 类重写了其超类 Animal 的 move 方法。但是它使用 super 关键字调用了父类的 move() 方法,因此当子类方法被调用时,由于动态绑定,两个 move 方法都会被调用。在 main() 方法中,我们使用 Animal 类的引用,并赋给它一个 Dog 类的对象来测试动态绑定的效果。
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move();
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog();
b.move();
}
}
输出:
Animals can move
Dogs can walk and run