Java的所有函数,除了声明为final的函数之外,都属于后期绑定,后期绑定动作会自动发生。
final的作用是禁止对函数进行覆写(overridding),而且告诉编译器该函数不需要后期绑定,程序从而可以获得较佳的效能,但实际上这么做并不会带来程序整体效能的提升。
例:
class A {
public void play() {
System.out.println(“A is running.“);
}
class B extends A {
public void play() {
System.out.println(“B is running.“);
}
class C extends A {
public void play() {
System.out.println(“C is running.“);
}
public class TestLateBinding {
static void play(A a) {
a.play();
}
public static void main(String[] args) {
play(new A());
play(new B()); // late binding
play(new C()); // late binding
}
}
public void play() {
System.out.println(“A is running.“);
}
class B extends A {
public void play() {
System.out.println(“B is running.“);
}
class C extends A {
public void play() {
System.out.println(“C is running.“);
}
public class TestLateBinding {
static void play(A a) {
a.play();
}
public static void main(String[] args) {
play(new A());
play(new B()); // late binding
play(new C()); // late binding
}
}