Is this the way Constructor in Java allocates memory?

前端 未结 5 1760
遥遥无期
遥遥无期 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:16

    But in Java when we allocate memory using new operator i.e. classname obj=new classname(); the constructor is automatically invoked before new allocates memory to the class member's.

    That is incorrect. The constructor is invoked after memory has been allocated.

    @Jon Skeet's answer explains clearly the sequence of events that occur during object creation.

    You may be confused by the fact that the constructors may well cause further objects to be allocated; e.g. during the execution of the declaration initializers. But these objects don't occupy memory in the original object; i.e. the object we are constructing.


    If you want a definitive specification of what happens when an object is created, read the Java Language Specification - in particular JLS 12.5.

提交回复
热议问题