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 对象字段是用什么初始化的?


- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01