When are initializations outside a constructor called?

前端 未结 2 961
有刺的猬
有刺的猬 2021-01-13 19:51

Suppose I have

class MyObject
{
    Object object1 = new Object();
    Object object2;

    public MyObject()
    {
        object2 = new Object();
    }

           


        
相关标签:
2条回答
  • 2021-01-13 20:10
    • 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.

    0 讨论(0)
  • 2021-01-13 20:10

    If you want to confirm behavior, use javap or a similar tool to inspect the bytecode. Though Jon is correct, refer to the specification as a 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
    
    0 讨论(0)
提交回复
热议问题