Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I initialize variable within constructor or outside constructor [duplicate]

Tags:

java

People also ask

Do you have to initialize all variables in constructor?

You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.

Can we initialize variable in constructor?

Yes, you can also initialize these values using the constructor.

Which variables are initialized inside a method block or constructor?

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Why do we initialize in constructor?

A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.


I find the second style (declaration + initialization in one go) superior. Reasons:

  • It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
  • If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).

Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.


I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.

As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.


I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.

For example in your second snippet, you can remove the constructor and have a clearer code.


If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.

class String
{
    char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
    String()
    {
        this.arr=new char[0];
    }
    String(char[] arr)
    {
        this.arr=arr;
    }
}

So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.

FYI other option's for initialization without using a constructor :

class Foo
{
    int i;
    static int k;

    //instance initializer block
    {
        //run's every time a new object is created
        i=20;
    }

    //static initializer block
    static{
        //run's only one time when the class is loaded
        k=18;
    }    
} 

The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.


I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.

Either way will work, and it's a matter of style, but I prefer constructors for member initialization.