gpt4 book ai didi

java - 为什么 "reinitialise the class variable"当只有一个类变量的副本在这个特定类的所有实例之间共享时

转载 作者:行者123 更新时间:2023-11-30 06:10:32 25 4
gpt4 key购买 nike

我是 Java 的新手,正在尝试学习静态初始化 block 的概念。我从 Java 教程 oracle 中看到了下面的代码和语句。我的问题是,为什么教程说:

"the advantage of private static methods is that they can be reused later if you need to reinitialise the class variable"

当这个特定类的所有实例之间只共享一个类变量副本时?

class Whatever {
public static varType myVar = initializeClassVariable();

private static varType initializeClassVariable() {

// initialization code goes here
}
}

最佳答案

有时您想将静态变量重置为其初始值。一个示例可能是您希望不时重置的全局计数器

class Whatever {

private static int counter = getCountInit();

public static resetCounter() {
counter = getCountInit();
}

private static getCountInit() {
return 0; // or some fancy computation
}

}

另一个例子是测试:假设你有一个测试用例 A,它改变了一个类的一些静态变量,还有一个测试用例 B 也使用了这个静态变量。如果不将静态变量设置回初始值,测试的结果将根据它们运行的​​顺序而有所不同。(旁注:这就是为什么拥有全局状态(静态变量是全局状态)通常不是一个好主意的一个主要原因 - 至少在较大的软件项目中是这样。)

关于java - 为什么 "reinitialise the class variable"当只有一个类变量的副本在这个特定类的所有实例之间共享时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665948/

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