When is initialization outside the called constructor?

Let's pretend that

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 is object1 initialized? Before object2 , after object2 , depends?

What happens if I have a constructor that conflicts with the global definition of object1 , for example. in the third constructor above. What value does object take?

This does not cause me any problems, but I just wanted to understand the language a little. I like to know these little things so that I can later use them later.

+4
source share
2 answers
  • Variables are initialized with default values ​​for their type (0, zero, etc.)

  • The superclass constructor is called first. If the constructor of the superclass calls any virtual methods overridden in this class, the override will see the default values, regardless of the variable initializers or initializations in the constructor body.

  • Then the variable initializers are executed.

  • Then the constructor body is executed.

So, if you change the value of the variable inside the constructor body, any value set by the variable initializer will be overwritten. (The previous value could be used in other chain constructors, etc., of course.)

See section 12.5 of the JLS for details.

+6
source

If you want to confirm the behavior, use javap or a similar tool to check for bytecode. Although John is correct , refer to the specification as the first port of call.

 Compiled from "MyObject.java" class MyObject { java.lang.Object object1; java.lang.Object object2; public MyObject(); Code: 0: aload_0 1: invokespecial #11 // Method java/lang/Object."<init>":()V 4: aload_0 5: new #3 // class java/lang/Object 8: dup 9: invokespecial #11 // Method java/lang/Object."<init>":()V 12: putfield #13 // Field object1:Ljava/lang/Object; 15: aload_0 16: new #3 // class java/lang/Object 19: dup 20: invokespecial #11 // Method java/lang/Object."<init>":()V 23: putfield #15 // Field object2:Ljava/lang/Object; 26: return 
+1
source

All Articles