Is this the way Constructor in Java allocates memory?

前端 未结 5 1803
遥遥无期
遥遥无期 2021-01-07 04:45

Default constructor is automatically called after an object is created.

But in Java when we allocate memory using new operator i.e. classname obj = new classna

5条回答
  •  无人及你
    2021-01-07 05:31

    The process is basically:

    • Memory is allocated
    • Execution goes up the constructor chain (i.e. all the this / super calls to other constructors) each level evaluating any arguments to the level above, but that's all
    • Execution goes down the constructor chain for the actual constructor bodies. So the body of the java.lang.Object constructor is executed first, then the direct subclass, etc. This is also when variable initializers are executed. (Prior to this, the variables have their default values of null etc.)
    • The reference is returned to whoever called new

    The idea of a default constructor has no meaning at execution time. It's just a parameterless constructor which calls super() as far as the JVM is concerned.

    The business about the constructor chain is exactly the same as it would be if these were methods with a first line which just chains to the next constructor along; it's just a stack of calls.

提交回复
热议问题