此文章为转载.原做者我经过Google为能找到.由于相同的文章太多.但限于此博文内容简洁明了.故此转载.对做者表示敬意.html
程序绑定的概念:
绑定指的是一个方法的调用与方法所在的类(方法主体)关联起来。对java来讲,绑定分为静态绑定和动态绑定;或者叫作前期绑定和后期绑定。 java
静态绑定:
在程序执行前方法已经被绑定,此时由编译器或其它链接程序实现。例如:C。
针对Java简单的能够理解为程序编译期的绑定;这里特别说明一点,java当中的方法只有final,static,private和构造方法是前期绑定。 网络
动态绑定:
后期绑定:在运行时根据具体对象的类型进行绑定。
若一种语言实现了后期绑定,同时必须提供一些机制,可在运行期间判断对象的类型,并分别调用适当的方法。也就是说,编译器此时依然不知道对象的类型,但方法调用机制能本身去调查,找到正确的方法主体。不一样的语言对后期绑定的实现方法是有所区别的。但咱们至少能够这样认为:它们都要在对象中安插某些特殊类型的信息。this
Java的方法调用过程:spa
动态绑定的过程:code
Parent obj = new Children();
public class Father { public void method() { System.out.println("父类方法,对象类型:" + this.getClass()); } }
public class Son extends Father { public static void main(String[] args) { Father sample = new Son();// 向上转型 sample.method(); } }
public class Son extends Father { public void method() { System.out.println("子类方法,对象类型:" + this.getClass()); } public static void main(String[] args) { Father sample = new Son();//向上转型 sample.method(); } }
public class Father { protected String name="父亲属性"; public void method() { System.out.println("父类方法,对象类型:" + this.getClass()); } }
public class Son extends Father { protected String name="儿子属性"; public void method() { System.out.println("子类方法,对象类型:" + this.getClass()); } public static void main(String[] args) { Father sample = new Son();//向上转型 System.out.println("调用的成员:"+sample.name); } }
public class Father { protected String name = "父亲属性"; public String getName() { return name; } public void method() { System.out.println("父类方法,对象类型:" + this.getClass()); } }
public class Son extends Father { protected String name="儿子属性"; public String getName() { return name; } public void method() { System.out.println("子类方法,对象类型:" + this.getClass()); } public static void main(String[] args) { Father sample = new Son();//向上转型 System.out.println("调用的成员:"+sample.getName()); } }
结果:调用的是儿子的属性。