When is better to insantiate an instance variable/object in the constructor vs before the constructor

1760 views java
6

So I was working on a school project and was given the first few lines of code

ArrayList<Person> people;

public MyPersonListV1(){
    people = new ArrayList<Person>();
    //other stuff
}

I was wondering why you would instantiate the object in the constructor instead of above it with the declaration like this:

ArrayList<Person> people = new ArraList<Person>();

public MyPersonListV1(){        
    //other stuff
}

answered question

Because you prefer it that way, or because the initialization code depends on the arguments of the constructor, typically, or on another variable initialized in the constructor. You'll know when you'll have to.

1 Answer

6

It's up to your preference.

If you're interested, this answer provides thoughts as to why some people prefer to initialize variables outside of constructors, which are that it can be more clear, and if there are multiple constructors you may not have to repeat the initialization.

posted this

Have an answer?

JD

Please login first before posting an answer.