gpt4 book ai didi

java - 在类本身中创建一个实例

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:55 25 4
gpt4 key购买 nike

第4行执行赋值语句时发生了什么,编译器是否忽略new运算符并保持foo变量为null或发生了其他事情来处理这个尴尬的时刻?


public class Foo {
// creating an instance before its constructor has been invoked, suppose the "initializing"
// gets printed in constructor as a result of the next line, of course it will not print it
private Foo foo = new Foo();//Line 4

public Foo() {
System.out.println("initializing");
}
}

最佳答案

编译器在这里没有做任何特别的事情。它可能会警告您这行不通,但这很难确定。

您将收到 StackOverflowError。

public class Foo {
private Foo foo = new Foo();//Line 4

public Foo() {
System.out.println("initializing");
}

public static void main(String... args) {
Foo foo = new Foo();
}
}

打印

Exception in thread "main" java.lang.StackOverflowError
at Foo.<init>(Foo.java:9)
at Foo.<init>(Foo.java:7)
at Foo.<init>(Foo.java:7)
.. many deleted ...
at Foo.<init>(Foo.java:7)
at Foo.<init>(Foo.java:7)

关于java - 在类本身中创建一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191995/

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