简体   繁体   English

当'new'运算符使用构造函数初始化内存时,JVM会做什么?

[英]What does the JVM do when 'new' operator initializes the memory using the constructor?

RealEstate v = new RealEstate();

I have used this new keyword with RealEstate() . 我在RealEstate()使用了这个new关键字。 I know new allocates memory and initializes the memory using the RealEstate class constructor. 我知道new分配内存并使用RealEstate类构造函数初始化内存。

What is the JVM doing here? JVM在这做什么?

new operator doesn't actually uses the help from constructor to allocate memory. new运算符实际上并没有使用构造函数的帮助来分配内存。 It has nothing to do with constructor. 它与构造函数无关。 Basically Java's version of malloc is new . 基本上Java的malloc版本是new

new operator: new运营商:

  • allocates memory for an object 为对象分配内存
  • invokes object constructor 调用对象构造函数
  • returns reference to that memory 返回对该内存的引用

Constructor is executed separately to perform any operations during initialization, like allocating values to objects and variables. 构造函数单独执行以在初始化期间执行任何操作,例如将值分配给对象和变量。 If no Constructor is defined, then compiler will create default constructor and will allocate default values: 如果没有定义构造函数,则编译器将创建默认构造函数并将分配默认值:


The following chart summarizes the default values for several data types. 下表总结了几种数据类型的默认值。 source 资源

Data Type   Default Value (for fields)
byte            0
short           0
int             0
long            0L
float           0.0f
double          0.0d
char            '\u0000'
String          null
any object      null
boolean         false

So, new operator only allocates memory and returns reference to that memory. 因此, new运算符仅分配内存并返回对该内存的引用。

See the documentation : 查看文档

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. new运算符通过为新对象分配内存并返回对该内存的引用来实例化一个类。 The new operator also invokes the object constructor. new运算符还调用对象构造函数。

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

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