什么是初始化的java对象字段? [英] What are java object fields initialized with?

查看:200
本文介绍了什么是初始化的java对象字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

null for Object type?

Is it null for Object type?

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

s 总是 null

如何将简单类型作为 INT ?那会是什么?零或任意值?

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;
}

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;
    }
}

哪个更好,为什么?

推荐答案

来自太阳报 java教程


在字段中并不总是需要分配
值宣布。声明但未初始化
的字段
将被编译器设置为
的合理默认值。一般来说,这个
默认值为零或null,
,具体取决于数据类型。然而,依赖于
这样的默认值是
通常被认为是错误的编程
样式。

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.

这篇关于什么是初始化的java对象字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆