开发者

What's the difference between non-initialisation and initialising to null?

开发者 https://www.devze.com 2023-01-24 04:17 出处:网络
I have this code: MyClass object; .... some code here where object may or may not be initialised... if (object.getId > 0) {

I have this code:

MyClass object;

.... some code here where object may or may not be initialised...

if (object.getId > 0) {
    ....
}

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) {
     ....
}
开发者_如何学Python

I get the same compile error! I have to initialise object to null:

MyClass object = 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?

Thanks


  • 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.


It's a language-definition thing.

The language states that variables of METHOD-scope MUST be manually initialized -- if you want them to start out as NULL, you must explicitly say so -- if you fail to do so, they are basically in an undefined state.

Contrarily, the language states that variables of CLASS-scope do not need to be manually initialized -- failure to initialize them results in them automatically getting initialized to NULL -- so you don't have to worry about it.

As far as the difference between the two states (null vs. undefined), yes they are basically the same -- but the language dictates that you need to initialize a variable (whether that's done automatically for you or not, depending on the variable's scope).


Your declaration of object is really a declaration of a pointer, or reference, to an instance of MyClass on the heap. If you don't initialize the pointer you essentially get a pointer pointing to somewhere random. By explicity initializing the pointer to NULL you are setting it to point to a NULL address that the compiler knows is invalid.

Extra confusion is introduced in Java because it implicitly initialises member variables to NULL for you.

It makes a bit more sense if you've used lower level languages like C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消