Java 超類中對子類方法的調(diào)用

  • 規(guī)則
    子類繼承了超類的方法,從子類中可以調(diào)用超類中的方法。通過查詢繼承樹實現(xiàn),先從當(dāng)前類中查找,如果沒有找到,向上回溯。

  • 實現(xiàn)
    為了能用簡便、面向?qū)ο蟮恼Z法來編寫代碼,即“發(fā)送消息給對象”,編譯器做了一些幕后工作,暗自把“所操作對象的引用”作為第一個參數(shù)傳遞給方法,就是this,P87 Thinkning in Java 第四版。也就是說以下代碼

class Banana {
  void peel(int t){}
}

public class BananaPeel{
  public static void main(String[] args){
    Banana a = new Banana();
    Banana b = new Banana();
    a.peel(1);
    b.peel(2);
  }
}

上述兩個方法的調(diào)用就變成了

Banana.peel(a, 1);
Banana.peel(b, 2);

對于實例方法,是調(diào)用this上的方法,因此調(diào)用子類的override方法

  • Static 方法
    首先看Static的含義。
    對于成員變量:為某個特定域分配單一存儲空間
    對于方法:即使沒有創(chuàng)建實例,也希望調(diào)用這個方法。所以,static 方法就是沒有this的方法,如果某個方法是靜態(tài)的,它的行為就不具有多態(tài)性。P157,Thinkning in Java 第四版。

對于實例方法,是調(diào)用this上的方法,因此調(diào)用超類的override方法

public class SuperClass {

    protected void outerM(){
        System.out.println("outer Method in Super Class!");
        System.out.println(this.getClass().toString());
        innerM();
    }

    protected void innerM(){
        System.out.println("inter Method in Super Class");
    }

    protected static void staticOuterM(){
        System.out.println("outer Method in static Super Class!");
        staticInnerM();
    }

    protected static void  staticInnerM(){
        System.out.println("inter Method in static Super Class");
    }
}

public class ChildClass extends SuperClass{

    protected void innerM(){
        System.out.println("inter Method in Child Class");
    }

    protected static void  staticInnerM(){
        System.out.println("inter Method in Child Class");
    }

    public static void main(String...strings){
        ChildClass cc = new ChildClass();
        cc.outerM();
        ChildClass.staticOuterM();
    }
}

輸出

outer Method in Super Class!
class zy.tijava.inherit.ChildClass
inter Method in Child Class
outer Method in static Super Class!
inter Method in static Super Class
  • Sub對象轉(zhuǎn)型為Super引用時,任何域訪問操作都將由編譯器解析,因此不是多態(tài)的。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容