繁体   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