This question already has an answer here:
-
What are the best practices for determining the tasks of Constructor, Initialization and Reset methods
5 answers
In Java, but in other OO languages as well, is there a difference between initializing an attribute in its definition, as in
class Example {
public Sample sample_attribute = new Sample();
}
and using a constructor to initialize it?
class Example {
public Sample sample_attribute;
public Example() {
sample_attribute = new Sample();
}
}
I could not think of any practical difference, is there one? Otherwise, are there cases in which one method is better than the other, even if they have the same result?
The initialization order is matter here.
- Set fields to default initial values (0, false, null)
- Call the constructor for the object (but don't execute the body of
the constructor yet)
- Invoke the constructor of the superclass
- Initialize fields using initializers and initialization blocks
- Execute the body of the constructor
So, first case will be initialize the variable sample_attribute
in 4th step, second will initialize the variable sample_attribute
in 5th step. It's all depends on your requirement.
If you want to access any of the variables from Constructor, you need to use 1st case.
When you initialize your fields with information which gets passed into the constructor, you have no other choice but to initialize in the constructor. Otherwise, I prefer initialization on the spot as it saves me lines of code I have to read later.
These two versions are equivalent. But if new Sample()
threw a checked exception you wouldn't be able to initialize it at field declaration