gpt4 book ai didi

java - “Few programmers are aware of the fact that a class' 的构造函数和方法可以在其初始化之前运行”

转载 作者:太空狗 更新时间:2023-10-29 22:32:40 25 4
gpt4 key购买 nike

在官方 Java 指南中 “Programming with assertions”据称(页面最后一段)

Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs.

这是什么意思?这是什么时候发生的?这是我日常使用 Java 时必须关心的事情吗?

最佳答案

基本上,他们谈论的是以下情况:

public class Foo {
public static Foo INSTANCE = new Foo(); // Prints null

public static String s = "bar";

public Foo() {
System.out.println(s);
}
}

如您所见,在这种情况下,构造函数在静态字段 s 的初始化程序之前运行,即。 e.在类的完全初始化之前。这只是一个简单的示例,但是当涉及多个类时,它会变得更加复杂。

这不是你在日常工作中经常看到的东西,但你需要意识到这种可能性,并在编写代码时避免它。

关于java - “Few programmers are aware of the fact that a class' 的构造函数和方法可以在其初始化之前运行”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172074/

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