gpt4 book ai didi

Java实例变量初始化方法

转载 作者:太空狗 更新时间:2023-10-29 22:50:38 24 4
gpt4 key购买 nike

我对下面这段代码有点困惑:

public class Test{

int x = giveH();
int h = 29;

public int giveH(){
return h;
}

public static void main(String args[])
{
Test t = new Test();
System.out.print(t.x + " ");
System.out.print(t.h);
}
}

这里的输出是0 29,但是我想这一定是编译器错误,因为在方法giveH() 的时候变量h应该还没有初始化。那么,编译是从上到下逐行进行的吗?为什么这是有效的?为什么 x 的值是 0 而不是 29?

最佳答案

int 的默认值为 0(参见 here)。因为您在 h 之前初始化了 x,所以 giveH 将返回 int 的默认值(例如 0)。

如果你这样调换顺序

int h = 29;
int x = giveH();

输出将是

29 29

关于Java实例变量初始化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33669037/

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