- Assign value to field at the same time with field declaration
- Assign value to field in the constructor?
Assign value to field at the same time with field declaration Assign value to
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Not much! The main difference is that if you assign it at the point of declaration, it will apply to all constructors. That is, there’s no way you can forget to add the initialization to any future constructors.
Have a look at the official Initializing Fields trail.
May be worth noting that if you initialize the fields at the declaration, it happens before the constructor starts executing.
As a rule of thumb, I usually initialize the “dead simple” fields at the declaration (when there is no doubt what the initial value should be). This “cleans up” For instance
while as if there is the slightest chance that I may want different behaviors in different constructors, I leave it to the constructor.