0

I'm used to C++, where you have to instantiate everything in the constructer, but a recent realization has made me very confused about java. I was just instantiating things in the constructer, and then I realized this syntax was valid:

public class DebateCompetition {
    private boolean isAdvanced;
    ArrayList<Debate> debates = new ArrayList<Debate>(); //<------
    ArrayList<Team> teams;
    ArrayList<School> schools;

    public void addSchool(School s) {
        schools.add(s);
    }
}

But that leaves a lot of questions. First: What does it do? Second: When is new ArrayList<Debate>() called? Third: Is this a best practice, or not?

sinθ
  • 11,093
  • 25
  • 85
  • 121
  • See http://stackoverflow.com/questions/4916735/default-constructor-vs-inline-field-initialization – flup Apr 26 '13 at 23:39

2 Answers2

6

First: What does it do?

All field initializers are executed (in order) before the code in the constructor is executed. (In this case you haven't declared a constructor, so there is a default no-args constructor which invokes the superclasses no-args constructor.)

Second: When is new ArrayList() called?

It is called during the instantiation of a new object.

The call happens after the superclass constructor has completed, and before executing the statements in this classes constructor. (In this case there are no statements in the constructor.)

Third: Is this a best practice, or not?

It is fine.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

It's the equivalent of innitializing these variables at the beginning of a constructor. If, in addition, you are using an instance initialization block, they are initialized before the initialization block is invoked. After executing the superclass constructor the order is: fields initialized in the class body, initialization blocks, the constructor body. If you only declare fields in the class body, the compiler automatically initializes them anyway, to their default values: null for Object, false for boolean etc.

luke657
  • 826
  • 2
  • 11
  • 28