-1

Where it is better to initialize fields? In constructor (var.1) or on declaration (var.2)?

var. 1

public class UtilWebLoading {
private int data;
private Context context;

public UtilWebLoading(Context context) {
    this.context = context;
    data = 100;
}
...
}

var. 2

public class UtilWebLoading {
private int data = 100;
private Context context;

public UtilWebLoading(Context context) {
    this.context = context;
}
...
}
Sviatoslav
  • 1,301
  • 2
  • 17
  • 42
  • I think you should look for a better example e.g. a list member with no constructor parameters, because in this case there is no real choice, since example 2 is wrong. – Tudor Jul 09 '12 at 13:19
  • 2
    possible duplicate of [Best Practice: Initialize class fields in constructor or at declaration?](http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration) – Denys Séguret Jul 09 '12 at 13:20

2 Answers2

13

In var. 1 the context has been initiated, while in var. 2 it will be null! Use the first one.

Carnal
  • 21,744
  • 6
  • 60
  • 75
  • It won't run, but if he would place Context context on top of the Util in var 2. it would run, but with null value. – Carnal Jul 09 '12 at 13:29
4

I personally prefer to initialize fields when I have sufficient context to do so. For example, if I have a List field I usually initialize it upon declaration (unless the class requires the user to pass an implementation of their choosing), but if I have an array that requires a size to be passed, I'm forced to wait for a constructor call.

Hence, in your case, the second snippet does not have enough context to initialize Util at declaration, because no valid Context member exists.

Tudor
  • 61,523
  • 12
  • 102
  • 142