1

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?

user5846939
  • 415
  • 4
  • 11
  • if it´s a literal or a constant it doesn´t matter. If it´s depending on a parameter then it should be in the constructor. (There are a few syntax error in your examples aswell as you might want to stick to the Java naming convention) – SomeJavaGuy Mar 01 '16 at 08:38

4 Answers4

1

You should do what you believe is simplest and cleanest. I prefer the first option as it is the simplest IMHO.

Otherwise it does the same thing.

So you are saying do not use the constructor for intialization?

In reality, the field initialisation all happens in the constructor at runtime.

I heard so often constructors are there for initializing variables, if not what else "should" be happening in the constructor do you mean?

So you are using the constructor in either way. Note: there is plenty you can't do on a simple one liner.

e.g.

public MyClass(int num) {
    this.num = num; // has to be in the constructor.
    try { // this could be in an initialiser block, but better here
        this.a = someOperation();
    } catch (IOException e) {
        // must be caught
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • So you are saying do not use the constructor for intialization? I heard so often constructors are there for initializing variables, if not what else "should" be happening in the constructor do you mean? – user5846939 Mar 01 '16 at 08:40
  • 1
    @OfeliavanAnalhard it´s there for variable initialization. But i think he meant to say it could be like the first one in case the variable isn´t depending on a parameter for initialization. – SomeJavaGuy Mar 01 '16 at 08:44
0

In the case of these particular fields, cpuCount doesn't look like it is going to change at runtime, so it might be a good candidate for the final keyword. This indicates that a value is a constant. There is a special naming convention for this approach, and an additional initialisation convention of doing it on the same line as the declaration.

private final int CPU_COUNT = 23;

However, the object and arrays you've got, look like they're going to be manipulated. So they should be initialised in the constructor.

private final int CPU_COUNT = 23;

public ComputerInsane() {
    this.someArray = new int[10];
    // etc
}

So your constant values are initialised inline, as is the norm with final values. Your other values are created in the constructor, because as you correctly said, this is a sound place to create instance variables.

Extra Reading

  • I'd strongly recommend you read the Java Naming Conventions. Your class names are a little off.

  • Have a read about the other uses of the final keyword here.

Community
  • 1
  • 1
christopher
  • 26,815
  • 5
  • 55
  • 89
0

It depends on what you want to do in future. Maybe you want to make a new constructor to multiply your count, like

public ComputerInsane (int multiCount){ }  

This way you could do

private int cpuCount = 23;

public ComputerInsane (int multiCount){ 
   cpuCount *= multiCount;
}  

or

private int cpuCount;

public ComputerInsane (int multiCount){ 
   cpuCount = 23 * multiCount;
} 

With the first solution you are not able to make cpuCount final, which you may want, the second solution supports cpuCount as a final field.

private final int cpuCount;

public ComputerInsane (int multiCount){ 
   cpuCount = 23 * multiCount;
} 
Don
  • 227
  • 1
  • 15
0

Initialization outside constuctor is executed before constructor body. It is important to understand if you have both initializations outside and inside constructors, so the constructor initialization executes last and overrides predefined value.

It's better to use initialization outside constructors if value is the same all the time, but if you have many constructors that initialize your field differently, so it's better to keep this logic inside constructors.