What are java object fields initialized with?(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.
这篇关于java 对象字段是用什么初始化的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java 对象字段是用什么初始化的?
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01