Lets say I have a class "ComputerInsane" with a private field "cpuCount" and a default constructor, like so:
public class ComputerInsane {
private int cpuCount = 23;
public ComputerInsane() {
//default constructor
}
}
Now I can either initialize cpuCount outside the constructor to the value of 23 like above, so that when I create an instance of the class computerInsane outside of the class the private field cpuCount will be automatically initialized to 23. I could however also put the initialization in the constructor after just having declared the variable, like so:
public class ComputerInsane {
private int cpuCount;
public ComputerInsane() {
//default constructor
cpuCount = 23;
}
}
This way it is also automatically called when I create an instance of the class computerInsane when the default constructor is called. My question is what is the actual difference between these two types of field initialization, should I do the first or the second variant?
More importantly, lets say the fields are objects of other classes that need to be initialized with "new", or arrays since they also need to be initialized with "new". In the same sense, do I then go:
public class ComputerInsane {
private int cpuCount = 23;
private int[] someArray = new int[10];
Someclass object1 = new Someclass();
public ComputerInsane() {
//default constructor
}
}
OR do I go:
public class ComputerInsane {
private int cpuCount;
private int[] someArray;
Someclass object1;
public ComputerInsane(){
//default constructor
cpuCount = 23;
someArray = new int[10];
object1 = new Someclass();
}
}
What is more preferrable, and what should I be doing?