1

When we write Instance variables in the body of the class and given that the constructor initializes them, then why can we Initialize the variables directly and outside the constructor without going to the constructor? isn't that the constructor's duty?

class Sample{
LinkedList<String> string=new LinkedList<>();//Initializing in the body of the class
String value="Hi";//Initializing in the body of the class

   public Sample(){
   //shouldnt string and value initialize here?}
}
amz
  • 32
  • 6
  • 1
    Does this answer your question? [Java order of Initialization and Instantiation](https://stackoverflow.com/questions/23093470/java-order-of-initialization-and-instantiation) – Amongalen Feb 12 '21 at 12:53

3 Answers3

1

Field initialization occurs before the constructor body is executed. It's helpful in some occasions, for example if you have multiple constructors, and the field should have the same initial value. In your example, you always want to start with an empty list, so you avoid null pointer exceptions. This is indeed a good practice for collections in general.

M A
  • 71,713
  • 13
  • 134
  • 174
  • Do you mean that after initializing variables in the body of the class, they will no longer take the default value in the default constructor? – amz Feb 12 '21 at 13:03
  • 2
    @amz No, the constructor body is executed after the field initialization, so the constructor can override the value. And important note: the constructor in your example is not a "default" constructor, it's actually referred to as a no-arg constructor. The default constructor is a constructor that Java creates automatically _if you don't define any constructor_. But even with a default constructor, its body still gets executed after all field initializations are done. – M A Feb 12 '21 at 13:09
0

Why can we? Because the language says you can.

That may be an unsatisfactory answer, but that's basically what it comes down to.

I view this as simply a matter of stylistic preference. For simple cases, particularly when I don't need any constructor with arguments, I'll use initializers (String foo = "bar") rather than do it in a constructor. For complex cases with many variables and more than one constructor, I'll maybe use initializers, and then have the constructors just deal with the values that need to be different. For in-between cases I tend to set it all up in the constructor(s).

user15187356
  • 807
  • 3
  • 3
0

Your question is more about software design. There are cases sometimes when you would need to have some default values for your object. I personally try to init values in constructor as much as possible. I think it's clearer as it's constructor's task to build a new instance of the object. Plus I believe it's good practice to try to make objects immutable, which means you have final fields and init them in the constructor. Of course, it's not always possible, but immutable objects prone to less bugs.

SergeiTonoian
  • 341
  • 2
  • 13