A is not static therefore not available in Class memory.
Correct. You have to have an instance of B
to get at the field A obj
.
will it be preinitialized for every object of B ?
Yes. A separate new A
will be created for every B
created.
If this has to stay in obj memory then when will this initialization happen ?
N/A
Either way is it a good practice ?
Yes. It's called object composition and composing objects from other objects is one of the two main means of decomposing a problem using Object-Oriented design. The other one is inheritance.
Then why do we have constructors if we can do this ?
This is just syntactic sugar. All the below are equivalent.
class B {
A obj = new A(); // field initializer
}
class B {
A obj;
B() {
A = new A(); // initialized in constructor
}
}
class B {
A obj;
{ obj = new A(); } // instance initializer
}
As long as nothing reads obj
during initialization, there's no observable difference between doing initialization in a field, constructor, or explicit initializer.
Sometimes it's just more convenient to assign a value where the field is declared.