If I define a class like following:
public class myClass {
private x = new anotherClass();
private y;
public myClass() {
y = new anotherClass();
}
}
which variable will get instance earlier? x or y?
And, is it unrecommended to assign a variable outside the constructor?
The order of execution is:
xin your code)yin your code)Section 12.5 of the Java Language Specification contains the details.
Whether you assign the variable in the constructor or not is up to you – I quite like a rule of thumb whereby if the initial value doesn’t depend on any constructor parameters, and will always be the same for all constructors, use a variable initializer. Otherwise, assign it in a constructor.