簡體   English   中英

Java中對super()的構造函數調用順序

[英]Order of Constructor Call for super() in Java

我試圖解釋為什么這段代碼沒有返回我期望的結果:

public class Bike {
    int height;
    int color;
    public Bike(int height, int color) {
        this.height = height;
        this.color = color;
    }
}

public class MountainBike extends Bike {
    public MountainBike(int height, int color) {
        super(height, color);
        super.height = 200;
        System.out.println(super.height);
        System.out.println(height);
    }
}

public class Main {

    public static void main(String[] args) {
        MountainBike a = new MountainBike(1, 1);

    }
}

哪個返回

200
1

我期望System.out.println(height)打印200但是只有超級調用可以。

操作順序為:

0. all fields including superclass fields are declared and memory is allocated

1. super() call from MountainBike constructor is called

2. super() call from Bike constructor is called

3. Object super() call is called

4. Bike fields are initialized (nothing happens in this case)

5. Bike constructor is executed (height and color are set to arguments from the super() call from MountainBike)

6. MountainBike fields are initialized (nothing happens in this case)

7. MountainBike constructor is executed (should set super.height to 200 and then both System.out.println calls should return 200)

在這種情況下,有人可以指出我的錯誤嗎?

System.out.println(height); MountainBike構造函數中,將打印傳遞給該構造函數的參數的值為1。面對具有相同名稱的多個變量,Java將首先在范圍內使用“最接近”。

您在做什么與構造函數的順序無關。

您正在通過參數“隱藏”該字段。 現在您正在更新該字段,並且僅更新該字段。

您將打印字段,然后打印參數,該參數仍然是傳遞給構造函數的原始值。

順便說一句:首先執行Bike的構造函數。

暫無
暫無

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

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