简体   繁体   English

在堆上创建对象(Java)之后是否调用对象的构造函数?

[英]Is the constructor for an object invoked after object creation on heap (Java)?

When you instantiate a new object by calling constructor, ie Foo bar = new Foo(var); 当通过调用构造函数实例化新对象时,即Foo bar = new Foo(var);

When does the code in the constructor actually gets invoked in relations to object creation heap? 构造函数中的代码何时真正在与对象创建堆的关系中被调用? When the constructors modifies member variables of bar, is storage for the variables already allocated and contain default values? 当构造函数修改bar的成员变量时,是否已经存储了已分配的变量并包含默认值?

Once new is called it knows how much memory needs to be allocated into the heap for a variable of type, in your case Foo. 一旦调用new ,它将知道需要为堆中的类型变量(例如Foo)分配多少内存。 Once that memory is allocated only then are the values set. 一旦分配了该内存,便会设置值。 Think about it how else are you going to assign member variables if you don't have memory for the member variable? 考虑一下,如果没有足够的成员变量存储空间,该如何分配成员变量? If there is no memory new will throw an exception which you need to handle. 如果没有内存,则new会引发您需要处理的异常。

Process: 处理:

  1. JVM sees new JVM看到了new
  2. Allocates memory on the heap to store the object (Ref type) 在堆上分配内存以存储对象(引用类型)
  3. Assigns default values 分配默认值
  4. If of object type assigns null 如果对象类型为null
  5. Call constructor 调用构造函数

当JVM遇到new关键字时,它将为该类类型分配所需的内存,如果没有初始化,则它将所有成员初始化为其默认值,如果该成员是一个对象,则将其初始化为null。

Here Foo bar = new Foo(var); 这里Foo bar = new Foo(var); we are creating bar object.When we use new keyword memory is allocated on the heap.The amount of memory allocated depends on the instance variables of the class.The JVM will calculate the amount of memory to be allocated, then using new it will allocate the memory.Here bar is a reference variable pointing on the heap where the object is allocated. 我们正在创建bar对象。当我们使用new关键字在堆上分配内存时,分配的内存量取决于该类的实例变量.JVM将计算要分配的内存量,然后使用new它将分配此处的条是指向对象分配到的堆上的引用变量。

The constructor cannot be called until the memory exists. 直到内存存在,才能调用构造函数。

For member variables, it is a recursive application of the same rule. 对于成员变量,这是相同规则的递归应用。

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

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