该绑定方法是多太实现的关键,java中除了static和final(private方法属于final方法)之外,其它所有的方法都是后期绑定,将方法声明为final就是为了防止其他人覆盖该方法,更重要的是:这样做能有效的“关闭”动态绑定。比如下面的实例
(1):会输出father,因为没有动态绑定
public
class Father {
protected static void
print() {
System.out.println("Father");
}
}
public
class Child2
extends
Father {
protectedstaticvoid
print() {
System.out.println("Child");
}
publicstatic
voidprint2(Father f) {
f.print();
}
publicstaticvoid
main(String[] args) {
Father f =
new
Child2();
print2(f);
}
}
(2)普通的方法形式,输出child,因为没有定义为static
public
class Father {
protectedvoidprint()
{
System.out.println("Father");
}
}
public
class Child2
extends
Father {
protectedvoidprint()
{
System.out.println("Child");
}
publicstatic
voidprint2(Father f) {
f.print();
}
publicstaticvoid
main(String[] args) {
Father f =
new
Child2();
print2(f);
}
}