Suppose I have
class MyObject
{
Object object1 = new Object();
Object object2;
public MyObject()
{
object2 = new Object();
}
public MyObject(Object object2)
{
this.object2 = object2;
}
public MyObject(Object object1, Object object2)
{
this.object1 = object1;
this.object2 = object2;
}
}
When does object1 get initialized? Before object2, after object2, depends?
What happens if I have a constructor that conflicts with the global definition of object1, e.g. in the third constructor above. Which value does object take?
This isn’t causing me any problems but I just wanted to understand the language a bit better. I like to know these little things so that I could potentially make use of them later on.
The variables are initialized to the default values for their type (0, null etc)
First the superclass constructor is called. If the superclass constructor calls any virtual methods overridden in this class, the override will see the default values, regardless of any variable initializers or initialization in the constructor body.
Then variable initializers are executed.
Then the constructor body is executed.
So if you change the value of a variable within the constructor body, any value set by the variable initializer will be overwritten. (The previous value could have been used in other chained constructors etc, of course.)
See section 12.5 of the JLS for more details.