Possible Duplicate:
Should I initialize variable within constructor or outside constructor
I have here two examples on how to initialize a field (instance variable) in a class. My question is: what’s the difference between them? Which one is the best and why?
EXAMPLE 1:
public class Example1 {
private Object field;
public Example1() {
field = new Object();
}
}
EXAMPLE 2:
public class Example2 {
private Object field = new Object();
public Example2() {
}
}
Your first example is initializing the instance variables in the constructor.
The second example is initializing them when the class itself is instantiated, prior to the execution of code in your constructor, after the execution of any code in the superclass constructor. (If called.)
If you have instance variables that are always going to be initialized the same way regardless of which constructor is called, then you should use the second method. If the initialization of your instance variables depends on which constructor is called, then the first method is better. For example:
Note in the above example that you can actually use both – initialization in the constructor, and during the instantiation of your object.