標籤:pre int 引用 參數 聲明 動態 style on() new
繼承鏈中對象方法的調用規則:當前類-->父類-->爺類-->..-->祖先類(只能向上找,不能向下找)
優先順序:this.method(Obj) > super.method(Obj) > this.method((super)Obj) > super.method((super)Obj)
demo代碼:
public class Polymorphic {public static void main(String[] args) {Son son=new Son();Grandson grandson=new Grandson();Grandson2 grandson2=new Grandson2();son.method(); //this.method() 當前類Son有method(),就不在使用Father的method()了grandson.method(); //super.method() 當前類Grandson沒有method(),調用的是父類Son的method()grandson.methods(); //Grandson和Son都沒有methods(),向上找到Father的methods()grandson.method(grandson); //this.method((super)Obj) 當前類以及父類中沒有method(Grandson g),則找method(Son s)grandson2.method(son); //super.method((super)Obj) Grandson2和Son都沒有method(Son s),向上找到Father的method(Father f)/* 結果:* Son method()Son method()Father methods()G SF S*/Father father_son = new Son(); //聲明了一個Father對象,但建立了一個Son對象,father_son是對象的引用,指向建立的Son對象grandson.method(father_son); //結果:F F 因為參數代表的是聲明的對象,並非建立的對象}}class Father {public void method(){System.out.println("Father method()");}public void methods(){System.out.println("Father methods()");}public void method(Father f){System.out.println("F F");}public void method(Son s){System.out.println("F S");}}class Son extends Father{public void method(){System.out.println("Son method()");}}class Grandson extends Son{public void method(Son s){System.out.println("G S");}}class Grandson2 extends Son{}
java 動態綁定 多態