简体   繁体   English

构造函数的执行顺序和对象的创建

[英]Execution order of constructor and creation of object

Hi guys I am confused in a very common concept of java. 嗨,大家好我很困惑java的一个非常常见的概念。 Say, "A" is a class, so when compiler reached to the statement new A(); 说,“A”是一个类,所以当编译器到达语句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; 当语句A = new A()被调用时;

  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. JVM搜索类A,如果类加载器尚未加载类A,则加载类A.此时调用类A中的static {}块。

  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. 在单线程应用程序中,序列将是:1)由类加载器加载的类(这里是所有静态初始化)2)创建的类实例3)返回并分配对此实例的指针,之后返回控件。

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. 所以内存是保留和填充的,后一部分是由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) 对象加载(首先执行IIB,然后分配给NS变量的值)
  3. Constructor called by "this" pointer 构造函数由“this”指针调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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