Variable default value

社会主义新天地 提交于 2019-12-02 01:29:02

问题


"It is important to point out that the content field of the template is by default set to null (as Java does with all noninitialized object fields upon creation)."

It is from book "JavaSpaces Principles Patterns and Practice"

Here is code:

public class Message implements Entry {
  public String content;
  public Message() {
  }
}

I wonder if this is true, because I watched somewhere on internet that this is not true?


回答1:


Yes, this is true, but it may not mean quite what you think it means. All object fields will be initialized to null if no value is specified, but primitive types have other default values. For instance, int fields default to 0, floats to 0.0, and booleans to false.

More information on these defaults here: http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.




回答2:


It is probably true, but if you really want to be sure that content starts as null, then set it explicitly. (Doing this also makes it more clear that your code intends content to be null initially.)

public String content = null;


来源:https://stackoverflow.com/questions/7018908/variable-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!