gpt4 book ai didi

java - 为什么我的初始化 block 向后运行?

转载 作者:行者123 更新时间:2023-11-30 07:46:10 24 4
gpt4 key购买 nike

这会打印出 r1 r4 pre b1 b2 r3 r2 hawk

但我不明白为什么它打印 r3 r2 而不是 r2 r3 ,这看起来是向后的。如果初始化 block 自上而下执行,为什么它从底部语句 r3 开始并以 r2 结束?在父类(super class) Bird 中,它按照我对 b1 和 b2 的预期执行,从上到下,但在父类(super class) Raptor 中,构造函数运行后,控制似乎首先跳转到最后一个语句,然后自行返回到顶部。有什么想法吗?

这让我发疯。

class Bird {
{ System.out.print("b1 "); }
public Bird()
{ System.out.print("b2 ");
}

class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor()
{System.out.print("r2 "); } // don't these two print backwards?
{System.out.print("r3 "); } // ???
static { System.out.print("r4 "); }
}

class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

最佳答案

你的类Raptor有一个初始化 block 。它被复制到构造函数中。

public Raptor()    
{System.out.print("r2 "); } // don't these two print backwards?
{System.out.print("r3 "); } // ???

成为

public Raptor() {
super();
System.out.print("r3 "); // <-- initialization block copied in.
System.out.print("r2 ");
}

这就是为什么你会得到你所做的输出。

关于java - 为什么我的初始化 block 向后运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930375/

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