用什么初始化java对象字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1913168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:49:11  来源:igfitidea点击:

What are java object fields initialized with?

javainitialization

提问by EugeneP

Is it nullfor Objecttype?

null为了Object类型吗?

class C {
    int i;
    String s;
    public C() {}
}

Will sbe always null?

s一直null吗?

What about simple types as int? What will that be? Zero or an arbitrary value?

简单类型怎么样int?那会是什么?零还是任意值?

What about local variables in methods?

方法中的局部变量呢?

public void meth() {
    int i;
}

What is the unitialized value of i?

的单位化值是i多少?



Relying on such default values, however, is generally considered bad programming style.

然而,依赖这样的默认值通常被认为是糟糕的编程风格。

Ok, what do you suggest we do?

好的,你建议我们做什么?

class A {
    String s = "";
    int i = 0;
}

OR:

或者:

class A {
    String s;
    int i;
    public A() {
        // default constructor
        s = "";
        i = 0;
    }
}

Which is better and why?

哪个更好?为什么?

回答by stimpie

From suns java tutorial

来自suns java教程

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

声明字段时并不总是需要赋值。已声明但未初始化的字段将由编译器设置为合理的默认值。一般而言,此默认值将为零或空值,具体取决于数据类型。然而,依赖这样的默认值通常被认为是糟糕的编程风格。

下图总结了上述数据类型的默认值。

Data Type   Default Value (for fields)
byte                    0 
short                   0   
int                     0 
long                    0L 
float                   0.0f 
double                  0.0d 
char                    '\u0000' 
boolean                 false
String (or any object)  null 

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

局部变量略有不同;编译器永远不会为未初始化的局部变量分配默认值。如果您无法在声明它的地方初始化您的局部变量,请确保在尝试使用它之前为其分配一个值。访问未初始化的局部变量将导致编译时错误。

回答by Ash

For member variables: The default value for String is null. The default value for primitives is 0 (or 0.0 for floating point values).

对于成员变量:String 的默认值为 null。基元的默认值为 0(或浮点值的 0.0)。

For local variables: You must explicitly initialise a local variable before using it.

对于局部变量:您必须在使用前显式初始化局部变量。

As to the second part of your question: You can always say String s = "";in the member variable definition, or s = "";in the constructor. Then you know it will have a non-null value. (Also, in your setter you'd need to ensure that someone doesn't try and set it back to null.)

至于你问题的第二部分:你总是可以String s = "";在成员变量定义中说,或者s = "";在构造函数中说。然后你知道它会有一个非空值。(此外,在您的 setter 中,您需要确保不会有人尝试将其设置回 null。)

回答by Joel

Fields:Objects default to null; ints, longs and shorts to 0; Strings to null; booleans to false. It's all here.

字段:对象默认为空;整数,多头和空头为 0;字符串为空;布尔值为假。这一切都在这里

The compiler will force you to initialise variables declared in methods, local variables, yourself.

编译器会强制你初始化方法中声明的变量局部变量,你自己。

回答by Bozho

Primitive fields are initialized to 0/ false. Objects are initialized to null. But frankly, you could have tried that one..

原始字段被初始化为0/ false。对象被初始化为null. 但坦率地说,你可以尝试那个..

回答by nd.

As for the setter-method question: The whole point of setters is that they can check if the object passed conforms to the requirements of the class. e.g.

至于setter-method问题:setter的全部意义在于他们可以检查传递的对象是否符合类的要求。例如

public void setS(String s) {
  if (s == null)
     throw new IllegalArgumentException("S must not be null");
  this.s = s;
}

Or, with Google Collections/Google Guava:

或者,使用 Google Collections/Google Guava:

public void setS(String s) {
  this.s = Preconditions.checkNotNull(s, "S must not be null");
}

Of course, you can define arbitrary constraints, e.g.:

当然,您可以定义任意约束,例如:

/**
 * Sets the foo. Legal foo strings must have a length of exactly 3 characters.
 */
public void setFoo(String foo) {
  if (foo == null)
     throw new IllegalArgumentException("Foo must not be null");
  if (foo.length() != 3)
     throw new IllegalArgumentException("Foo must have exactly 3 characters");
  ...

Of course in such a case you should alwaysstate the correct range of values for your properties in the JavaDoc of the setter and/or of the class.

当然,在这种情况下,您应该始终在 setter 和/或类的 JavaDoc 中为您的属性声明正确的值范围。

回答by Roland

JLS 4.12.5. Initial Values of Variables

JLS 4.12.5。变量的初始值

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

For type byte, the default value is zero, that is, the value of (byte)0.

For type short, the default value is zero, that is, the value of (short)0.

For type int, the default value is zero, that is, 0.

For type long, the default value is zero, that is, 0L.

For type float, the default value is positive zero, that is, 0.0f.

For type double, the default value is positive zero, that is, 0.0d.

For type char, the default value is the null character, that is, '\u0000'.

For type boolean, the default value is false.

For all reference types (§4.3), the default value is null.

每个类变量、实例变量或数组组件在创建时都使用默认值进行初始化(第 15.9 节、第 15.10.2 节):

对于byte类型,默认值为0,即(byte)0的值。

对于short类型,默认值为0,即(short)0的值。

对于 int 类型,默认值为 0,即 0。

对于 long 类型,默认值为零,即 0L。

对于 float 类型,默认值为正零,即 0.0f。

对于 double 类型,默认值为正零,即 0.0d。

对于char类型,默认值为空字符,即'\u0000'。

对于类型 boolean,默认值为 false。

对于所有引用类型(第 4.3 节),默认值为 null。