这个Java类中的最后一个成员怎么会是null呢?

huangapple go评论64阅读模式
英文:

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 代码。

  1. defaultAbcParameters 有可能为 null 吗?这不会在类加载时初始化吗?
  2. 这种初始化方式与在构造函数中初始化有什么不同?

感谢您的时间。

英文:

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.

  1. Is there any possibility for defaultAbcParameters to be null? Wouldn't this be initialized when the class gets loaded?
  2. How is this way of initialization different from initializing in the constructor?

Thanks for your time.

答案1

得分: 2

  1. 是的,如果构建器返回null。
  2. 区别在于你的变量是静态的,因此它被所有abc类的实例共享。如果你在构造函数中初始化,那么该变量就不再是静态的,它将每个类实例一份。
英文:
  1. Yes, if the builder returns null.
  2. 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.

huangapple
  • 本文由 发表于 2020年8月28日 14:23:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63628515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定