What is the difference between defining and initialising the member variables in the beginning of the class definition, and defining the member variables first and initialising the member variables in the constructor?
Say, for example:
public class Test {
private int foo = 123;
private boolean flag = false;
public void fooMethod() {...}
}
Versus:
public class Test {
private int foo;
private boolean flag;
public Test() {
foo = 123;
flag = false;
}
public void fooMethod() {...}
}
Thanks in advance.
In your example, the only difference is when they are initialized. According to the JLS, instance variables are initialized before the constructor is called. This can become interesting when you have super classes to deal with, as the initialization order isn’t always so obvious. With that, keep in mind “super” instance variables will still be initialized when no explicit super constructor is called.