非初始化和初始化为null之间有什么区别? [英] What's the difference between non-initialisation and initialising to null?
本文介绍了非初始化和初始化为null之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码:
MyClass object;
.... some code here where object may or may not be initialised...
if (object.getId > 0) {
....
}
导致编译错误: object
可能尚未初始化,这是公平的。
Which results in a compile error: object
may not have been initialised, which is fair enough.
现在我将我的代码更改为:
Now I change my code to this:
MyClass object;
.... some conditional code here where object may or may not be initialised...
if (object != null && object.getId > 0) {
....
}
我得到相同的编译错误!我必须将 object
初始化为null:
I get the same compile error! I have to initialise object
to null:
MyClass object = null;
那么不初始化对象和初始化为null之间的区别是什么?如果我声明一个没有初始化的对象,那么它不是null吗?
So what's the difference between not initialising an object, and initialising to null? If I declare an object without initialisation isn't it null anyway?
谢谢
推荐答案
- 字段(成员变量)初始化为
null
(或默认原始值,如果它们是基元) - 本地变量未初始化,您负责设置初始值。
- fields (member-variables) are initialized to
null
(or to a default primitive value, if they are primitives) - local variables are not initialized and you are responsible for setting the initial value.
这篇关于非初始化和初始化为null之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文