Java 超類中對子類方法的調用

  • 規則
    子類繼承了超類的方法,從子類中可以調用超類中的方法。通過查詢繼承樹實現,先從當前類中查找,如果沒有找到,向上回溯。

  • 實現
    爲了能用簡便、面向對象的語法來編寫代碼,即“發送消息給對象”,編譯器做了一些幕後工作,暗自把“所操作對象的引用”作爲第一個參數傳遞給方法,就是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);
  }
}

上述兩個方法的調用就變成了

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

對於實例方法,是調用this上的方法,因此調用子類的override方法

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

對於實例方法,是調用this上的方法,因此調用超類的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對象轉型爲Super引用時,任何域訪問操作都將由編譯器解析,因此不是多態的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章