0

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
}
Tony
  • 11
  • 2
    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. – JB Nizet Nov 03 '18 at 18:47

1 Answers1

-1

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.

AbsoluteSpace
  • 710
  • 2
  • 11
  • 21