When does the Constructor gets called in java?

前端 未结 10 1412
[愿得一人]
[愿得一人] 2020-12-16 02:14

When does the Constructor get called?

  1. Before object creation.
  2. During object creation.
  3. After object creation.
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 02:54

    At the byte code level.

    1. An object is created but not initialised.
    2. The constructor is called, passing the object as this
    3. The object is fully constructed/created when the constructor returns.

    Note: The constructor at the byte code level includes the initial values for variables and the code in the Java constructor. e.g.

    int a = -1;
    int b;
    
    Constructor() {
       super();
       b = 2;
    }
    

    is the same as

    int a;
    int b;
    
    Constructor() {
       super();
       a = -1;
       b = 2;
    }
    

    Also note: the super() is always called before any part of the class is initialised.


    On some JVMs you can create an object without initialising it with Unsafe.allocateInstance(). If you create the object this way, you can't call a constructor (without using JNI) but you can use reflections to initialise each field.

提交回复
热议问题