java的动态绑定和静态绑定

动态绑定:程序在运行时把方法和所属的类绑定。

静态绑定:程序在编译时就把方法和所属的类绑定了,如果是private、static、final 方法或者是构造器,则编译器明确地知道要调用哪个的方法。

 

Base instance =new Son()  //instance是Base类型,引用Son实例 。

运行是jv把静态方法和所属的类绑定,实例方法和所引用的实例绑定。

 

一、动态绑定的过程:

  1. 首先,编译器根据对象的声明类型和方法名,搜索相应类(Son)及其父类(Father)的“方法表”,找出所有访问属性为public的method方法。

    可能存在多个方法名为method的方法,只是参数类型或数量不同。

  2. 然后,根据方法的“签名”找出完全匹配的方法。

    方法的名称和参数列表称为方法的签名。

    在Java SE 5.0 以前的版本中,覆盖父类的方法时,要求返回类型必须是一样的。现在子类覆盖父类的方法时,允许其返回类型定义为原始类型的子类型。

 

二、动态绑定规则:

 

  1. 子类重写父类中的方法,调用子类中的方法

  2. 子类没有重写父类中的方法,所以到父类中寻找相应的方法

     3.动态绑定只是针对对象的方法,对于属性无效。因为属性不能被重写。

 

三、例子

 

 1//子类有重写

public class Father{ 2 public void method(){ 3 System.out.println("父类方法:"+this.getClass()); 4 } 5 } 6 public class Son extends Father{ 7 public void method(){ 8 System.out.println("子类方法"+this.getClass()); 9 } 10 public static void main(String[] args){ 11 Father instance = new Son(); 12 instance.method(); 13 } 14 } 15 //结果:子类方法:class Son

 

 

 1 //子类咩有重写
 2 public class Father{
 3     public void method(){
 4         System.out.println("父类方法:"+this.getClass());
 5     }
 6 }
 7 public class Son extends Father{
 8     public static void main(String[] args){
 9         Father instance = new Son();
10         instance.method();
11     }
12 }
13 //结果:父类方法:class Son

 

 

 1 //针对属性
 2 
 3 public class Father{
 4     public String name = "父亲属性";
 5 }
 6 public class Son extends Father{
 7     public String name = "孩子属性";
 8 
 9     public static void main(String[] args){
10         Father instance = new Son();
11         System.out.println(instance.name);
12     }
13 }
14 //结果:父亲属性

 

posted @ 2015-02-09 11:40  galaxy77  阅读(284)  评论(0编辑  收藏  举报