java的动态绑定和双分派.pdfVIP

  • 5
  • 0
  • 约5.7千字
  • 约 5页
  • 2017-06-07 发布于湖北
  • 举报
Java 的动态绑定与双分派 Java 的动态绑定 所谓的动态绑定就是指程执行期间(而不是在编译期间)判断所引用对象的实际类型,根据其实际的类型调用其相应的 方法。java 继承体系中的覆盖就是动态绑定的,看一下如下的代码: 1. class Father { 2. public void method(){ 3. System.out.println(This is Fathers method); 4. } 5. } 6. 7. class Son1 extends Father{ 8. public void method(){ 9. System.out.println(This is Son1s method); 10. } 11. } 12. 13. class Son2 extends Father{ 14. public void method(){ 15. System.out.println(This is Son2s method); 16. } 17. } 18. 19. public class Test { 20. public static void main(String[] args){ 21. Father s1 = new Son1(); 22. s1.method(); 23. 24. Father s2 = new Son2(); 25. s2.method(); 26. } 27. } 运行结果如下: This is Son1s method This is Son2s method 通过运行结果可以看到 ,尽管我们引用的类型是Father 类型的,但是运行时却是调用的它实际类型(也就是 Son1 和 Son2 )的方法,这就是动态绑定。在java 语言中,继承中的覆盖就是是动态绑定的,当我们用父类引用实例化子类时,会 根据引用的实际类型调用相应的方法。 1 / 5 java 的静态绑定 相对于动态绑定,静态绑定就是指在编译期就已经确定执行哪一个方法。在java 中,方法的重载(方法名相同而参数 不同)就是静态绑定的,重载时,执行哪一个方法在编译期就已经确定下来了。看一下代码: 1. class Father {} 2. class Son1 extends Father{} 3. class Son2 extends Father{} 4. 5. class Execute { 6. public void method(Father father){ 7. System.out.println(This is Fathers method); 8. } 9. 10. public void method(Son1 son){ 11. System.out.println(This is Son1s method); 12. } 13. 14. public void method(Son2 son){ 15. System.out.println(This is Son2s method); 16. } 17. } 18. 19. public class Test { 20. public static void main(String[] args){ 21. Father father = new Father();

文档评论(0)

1亿VIP精品文档

相关文档