Is there any difference between these two ways of initialising class members?
In the class body:
public class A { private mB = new B(); public A() { } } Or in the constructor:
public class A { private mB = null; public A() { mB = new B(); } } Is there any difference between these two ways of initialising class members?
In the class body:
public class A { private mB = new B(); public A() { } } Or in the constructor:
public class A { private mB = null; public A() { mB = new B(); } } In theory, there is a difference in the sequence of initialization. This is the sequence used by the JVM:
Also, if you initialize the fields in the constructor, it can mean that you might get some duplication. Personally, I think it doesn't matter much where you instantiate them, either in the constructor or in the fields, but the main point is that you are consistent about it. For me it helps having them instantiated in the field declaration so I know which fields are always there, and which fields are optional. Hope that helps!
The instance initializer run first and then values in constructor are initialized. You can study order of execution of initialization blocks and constructors