简体   繁体   中英

Execution order of constructor and creation of object

Hi guys I am confused in a very common concept of java. Say, "A" is a class, so when compiler reached to the statement new A(); two things will happen

  1. object creation (because of new keyword)
  2. constructor calling.

The only point for which i am looking (confused) is "What will be the execution sequence???"

Object creation will be happen before constructor calling or constructor will be called before the object creation???

When the statement A = new A() is called;

  1. the JVM searches for the class A, if classloader haven't load class A yet, load class A. at that time static{} block in class A is called.

  2. Then memory is allocated (Is it refer to your "object creation"?)

  3. Then constructor is called. (which constructor is running)

Execution process is -

  1. The object memory is allocated
  2. the field variables with initial values are initialized and then the constructor is called, but its code is executed after the constructor code of the object super class.

In single thread application the sequence will be: 1) Class loaded by class loader (here are all static initializations) 2) Class instance created 3) Pointer to this instance returned and assigned, after this the control is returned.

In multithreaded environment things are not so simple, at list race conditions does matter.

The constructor is called on the instance during logical object creation.
So memory is reserved and populated, the latter part being done in part by the contstructor.

All that of course after the class instance has been created.

It gets more convoluted if there's a class hierarchy your class is a part of, as then the constructor will upon being called itself call its superclass constructor(s).

Ok got the answer guys. Thanks. Compiling the points as:

  1. Class loads (with static members)
  2. Object loads (First IIB executes, then values assigned to the NS variables)
  3. Constructor called by "this" pointer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM