Java后期绑定

来源:互联网 发布:mac 图形驱动 编辑:程序博客网 时间:2024/05/01 04:08

该绑定方法是多太实现的关键,java中除了staticfinalprivate方法属于final方法)之外,其它所有的方法都是后期绑定,将方法声明为final就是为了防止其他人覆盖该方法,更重要的是:这样做能有效的关闭动态绑定。比如下面的实例

1):会输出father,因为没有动态绑定

publicclass Father {

      protected static voidprint() {

             System.out.println("Father");

      }

}

publicclass Child2extends Father {

      protectedstaticvoidprint() {

             System.out.println("Child");

      }

      publicstatic voidprint2(Father f) {

             f.print();

      }

      publicstaticvoidmain(String[] args) {

             Father f =new Child2();

             print2(f);

      }

}

2)普通的方法形式,输出child,因为没有定义为static

publicclass Father {

      protectedvoidprint() {

             System.out.println("Father");

      }

}

publicclass Child2extends Father {

      protectedvoidprint() {

             System.out.println("Child");

      }

      publicstatic voidprint2(Father f) {

             f.print();

      }

      publicstaticvoidmain(String[] args) {

             Father f =new Child2();

             print2(f);

      }

}

0 0