gpt4 book ai didi

java - 多少次运行静态对象构造?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:12 26 4
gpt4 key购买 nike

对java和static变量有点疑惑。我有类似的问题,问题是:MyObject() 构造函数只运行一次或每次我创建 MyClass 的新实例时运行?

public class MyClass{    
static MyObject obj = new MyObject();
...

谢谢!

最佳答案

MyObject() constructor runs only once or every time I create a new instance of MyClass?

它仅在执行过程(类初始化)开始并在所有实例之间共享(单个副本)时运行一次。

A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7

关于java - 多少次运行静态对象构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20909711/

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