英文:
How can this final member in a Java class be null?
问题
抱歉,刚开始学习Java。
我有一个像这样的代码:
public class abc implements xyz {
private final static ABCParameters defaultAbcParameters = ABCParameters.newBuilder()
....
....
.build();
...
...
}
ABCParameters 是一个谷歌的 protobuf 消息,我们有这个消息生成的 JAVA 代码。
- defaultAbcParameters 有可能为 null 吗?这不会在类加载时初始化吗?
- 这种初始化方式与在构造函数中初始化有什么不同?
感谢您的时间。
英文:
Sorry, new to Java.
I have a code like this:
public class abc implements xyz {
private final static ABCParameters defaultAbcParameters = ABCParameters.newBuilder()
....
....
.build();
...
...
}
ABCParameters is a google protobuf message, and we have the generated JAVA code for that.
- Is there any possibility for defaultAbcParameters to be null? Wouldn't this be initialized when the class gets loaded?
- How is this way of initialization different from initializing in the constructor?
Thanks for your time.
答案1
得分: 2
- 是的,如果构建器返回null。
- 区别在于你的变量是静态的,因此它被所有abc类的实例共享。如果你在构造函数中初始化,那么该变量就不再是静态的,它将每个类实例一份。
英文:
- Yes, if the builder returns null.
- The difference is that your variable is static so it is shared by all the instances of the abc class. If you would initialise in the constructor, then the variable wouldn't be static anymore and it would be one per class instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论