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

2022-01-18 00:00:00 initialization java

Object 类型是 null 吗?

C 类 {诠释我;字符串 s;公共 C() {}}

s 会一直是 null 吗?

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

方法中的局部变量呢?

public void meth() {诠释我;}

i的单位化值是多少?

<小时><块引用>

然而,依赖这样的默认值通常被认为是不好的编程风格.

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

A 类 {字符串 s = "";诠释 i = 0;}

或者:

A 类 {字符串 s;诠释我;公共A(){//默认构造函数s = "";我 = 0;}}

哪个更好,为什么?

解决方案

来自 suns java教程

<块引用>

并不总是需要分配一个声明字段时的值.字段已声明但未初始化的将被设置为合理的默认值编译器.一般来说,这默认为零或空,取决于数据类型.靠然而,这样的默认值是通常被认为是糟糕的编程风格.

下面的图表总结了上述数据的默认值类型.

数据类型默认值(用于字段)字节 0短 0整数 0长0L浮动 0.0f双0.0d字符 'u0000'布尔假字符串(或任何对象) null

<块引用>

局部变量略不同的;编译器从不分配未初始化的默认值局部变量.如果你不能初始化你的局部变量它已声明,请确保分配它尝试使用它之前的值.访问未初始化的本地变量将导致编译时错误.

Is it null for Object type?

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

Will s be always null?

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

What about local variables in methods?

public void meth() {
    int i;
}

What is the unitialized value of 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?

解决方案

From suns java tutorial

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.

相关文章