gpt4 book ai didi

Java-为什么打印 null?

转载 作者:搜寻专家 更新时间:2023-10-31 08:12:42 25 4
gpt4 key购买 nike

public class Base {
public Base() {
x = 0;
bar();
}

public Base(int x) {
this.x = x;
foo();
}

public void foo() {
System.out.println("Base.foo : " + x);
}

private void bar() {
System.out.println("Base.bar:" + x.toString());
}

protected Integer x;
}

public class Derived extends Base {
public Derived() {
bar();
}
public Derived(int x, int y) {
super(x);
this.y = y;
}
public void foo() {
System.out.println("Derived.foo : " + x + ", " + y);
}
public void bar() {
System.out.println("Derived.bar:" + x.toString() + ", " + y.toString());
}
private Integer y;


public static void main(String[] args) {
Base b = new Derived(10, 20);
}
}

为什么它打印 "Derived.foo:"10, nulll 而不是 20 而不是 null?y 是 Derived 的私有(private)变量,它被初始化为 20。它在它的范围内.. 那为什么它是 null?

最佳答案

因为 super 构造函数首先被调用(super(x))。这个 super 构造函数调用方法 foo。然后 Derived 构造函数将 y 初始化为 20 (this.y = y)。所以当 foo 被调用时,y 还没有被初始化。

在构造函数中调用可重写的方法是一种不好的做法,因为正如您刚刚注意到的,它可以在部分构造的对象上调用重写的方法。

关于Java-为什么打印 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com