explicitly initialising member vars - necessary?

A

Alex Hunsley

A question on "correctness" of java code here....
I've been lead to believe that declaring class member variables without
explicitly initialising them (even to null or 0) is a Bad Thing(tm),
i.e. you should write:

private int count = 0;

and not just

private int count;

However, my understanding of the java spec is that it does specify that
member variables that aren't explicitly initialised get initialised to 0
or null. So can anyone give me a good reason to always explicitly
initialise member vars?

thanks
 
V

VisionSet

Alex Hunsley said:
A question on "correctness" of java code here....
I've been lead to believe that declaring class member variables without
explicitly initialising them (even to null or 0) is a Bad Thing(tm),
i.e. you should write:

private int count = 0;

and not just

private int count;

However, my understanding of the java spec is that it does specify that
member variables that aren't explicitly initialised get initialised to 0
or null. So can anyone give me a good reason to always explicitly
initialise member vars?

explicit - to show that you really want the attribute to have that value, it
has meaning in your code, you will probably make use of that value, whatever
that value is, even the default eg zero/null.

implicit - the implicit value (eg zero/null) is not meaningful, it is likely
that you will take care of initialisation elsewhere eg in the constructor.
 
M

Michael Borgwardt

Alex said:
However, my understanding of the java spec is that it does specify that
member variables that aren't explicitly initialised get initialised to 0
or null. So can anyone give me a good reason to always explicitly
initialise member vars?

It might make the code more readable to people who don't know the spec well.
 
P

Phil...

This might be bad if you feel obligated to provide a value
in situations where you have no idea of what the value will
be set to later thus misleading the reader who might be trying
to read some meaning into the init value.
 
S

Sudsy

Phil... said:
This might be bad if you feel obligated to provide a value
in situations where you have no idea of what the value will
be set to later thus misleading the reader who might be trying
to read some meaning into the init value.

Don't think so...it's called a variable for a reason. If it
gets changed anywhere in processing then it's performing the
intended task. Add the final qualifier if you need to make
it immutable. Fair enough?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top