簡體   English   中英

Java:從超類構造函數中的子類調用的方法

[英]Java:Method called from subclass in superclass constructor

class AA{
    int x;
    protected AA(){init (1008);}
    protected void init(int x)
    {
        this.x = x;
    }
}

class BB extends  AA{
    public BB() {
        init(super.x * 2);
    }
    public void init(int x)
    {
        super.x = x+1;
    }
}
public class Main  {

    public static void main(String[] args) {
        BB tst = new BB();
        System.out.println(tst.x);
    }
}

我知道這段代碼將在2019年打印。但是我不明白為什么超類構造函數在被調用時會使用de子類中的init方法而不是超類中的init方法。

但是我不明白為什么超類構造函數在被調用時會使用de subclass中的init方法而不是超類中的init方法。

因為那是與正在構造的對象相關聯的對象。 超類構造函數中的this是對正在構造的子類對象的引用,因此,就像使用該引用進行的對init任何其他調用一樣,它也使用子類的init

請注意最后帶有注釋的行,這可能會有所幫助-注釋說明了這些行的輸出:

class AA{
    int x;
    protected AA() {
        System.out.println(this.getClass().getName()); // "BB"
        System.out.println(this instanceof BB);        // true
        init(1008);
    }
    protected void init(int x)
    {
        this.x = x;
    }
}
class BB extends  AA{
    public BB() {
        init(super.x * 2);
    }
    public void init(int x)
    {
        super.x = x+1;
    }
}
public class Main  {

    public static void main(String[] args) {
        BB tst = new BB();
        System.out.println(tst.x);
    }
}

這是因為子類可以覆蓋方法,因此通常最好避免從構造函數中調用非final ,非private方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM