此文章爲轉載.原做者我經過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()); } }
結果:調用的是兒子的屬性。