Reputation: 1503
I have a couple of questions about constructors in Java:
How are you supposed to initialise/create objects that the class relies on? For example, I have a DateTime object in my 'time' class. Should I have a private DateTime _date;
field as part of the class and then stick _date = new DateTime();
in the constructor? Or is it better to initialise this object in a relevant method?
What do you do if fields are supposed to be uninitialised when a new object of their class is created (i.e. their values are set later when methods of the class are invoked on the object)? In the constructor, do I initialise them to null or some nonsense value?
Thanks for your help.
Upvotes: 0
Views: 236
Reputation: 1994
initDefaults()
method which is called by the constructor, pl
null
value means or (if you can't avoid it) a special 'default' value, and how methods return values, e.g. Robert Martin recommends to rather return an empty array than null
for an empty list (that way you avoid NPEs).Good Luck :-)
Upvotes: 1
Reputation: 147144
It's the primary responsibility of the constructor to ensure that the instance is set up obeying the class invariants (unless it throws an exception). The invariants are probably going to be simpler if the fields are required to be nonnull. In general you want to avoid using null
. NPEs are really common, and shouldn't be.
(Also I strongly advise sticking with standard Java conventions.)
Upvotes: 1
Reputation: 1074058
Fundamentally, the answer to both questions is: It's up to you.
If you do private DateTime _date = new DateTime();
, that will happen as part of instance construction as though it were in the constructor (it will happen immediately before the step-by-step code in the constructor is run). I can't find that said baldly in the JLS (that doesn't mean it's not there), but it'll be somewhere in Section 8 and/or Section 15. So whether it's at the declaration or in the constructor is your call. It has the advantage that if you have multiple constructors, it will happen regardless of which one is called; it has the disadvantage of having the construction code in more than one place.
They are implicitly initialized to null
, 0
, false
, etc. (their "default value"), depending on what type they are, as part of the definition of the Java language. So you can explicitly initialize them to null
and such if you want for clarity, emphasis, readability, whatever, but it's not required.
Upvotes: 2
Reputation: 11486
In answer to your second question, you can explicitly set the fields that are objects to null
within the constructor. However, this is not needed because if you do not construct or create the object, it would automatically be set to null
. For example,
Public class MyClass {
private User user;
public MyClass(){
this.user;
}
}
The constructor above is same as:
public MyClass(){
this.user = null;
}
Upvotes: 1