I am a bit ashamed to ask that, being a Java programmer for years, but here goes:
Is there a difference between allocating objects during construction, and doing so directly when declaring the relevant field? That is, is there a difference between the following two:
public class MyClass{
MyObj obj=new MyObj();
}
AND
public class MyClass{
MyObj obj;
public MyClass() {
obj=new MyObj();
}
}
Of course, I assume this specific init's do not rely on outside parameters.
instance variable initialization done before constructor call
Its not good to do.
You can restrict user from call of const. if you want to perform certain operation before initialization.
Best Practice:
- Don't initialize with the default values in declaration (null, false, 0, 0.0...).
- Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
- If the value of the field changes because of a constructor parameter put the >initialization in the constructors.
- Be consistent in your practice. (the most important rule)
from here
No, there isn't. Except that if you add multiple constructors you'll have duplicate code.
An alternative is to use an initializer block
{
var = 1;
}
Reference: Initializing Fields
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With