这是Java中的构造方法分配内存的方式吗? [英] Is this the way Constructor in Java allocates memory?

查看:25
本文介绍了这是Java中的构造方法分配内存的方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建对象后会自动调用默认构造函数.

Default constructor is automatically called after an object is created.

但是在Java中,当我们使用新的运算符(即 classname obj = new classname(); )分配内存时,构造函数会在 new分配给类成员的内存之前自动调用.

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.

分配是在类实际存在之后开始的,但是如果新操作符在调用默认构造函数之后完成其处理,那么默认构造函数实际上是如何执行的,因为该类尚未实际存在?

The allocation starts after the class comes into physical existence but if new operator completes its process after default constructor is called, then how default constructor actually do so as the class has not come into physical existence?

有人可以用一个清晰​​的例子向我解释吗?

Can someone explain me the same using a clear example?

推荐答案

该过程基本上是:

  • 已分配内存
  • 执行在构造器链(即对其他构造函数的所有 this / super 调用)中以上,但仅此而已
  • 执行会沿实际构造函数主体的构造函数链下降 .因此,首先执行 java.lang.Object 构造函数的主体,然后执行直接子类,等等.这也是在执行变量初始值设定项时.(在此之前,变量的默认值为null等.)
  • 该引用将返回给称为 new
  • 的任何人
  • Memory is allocated
  • Execution goes up the constructor chain (i.e. all the this / super calls to other constructors) each level evaluating any arguments to the level above, but that's all
  • Execution goes down the constructor chain for the actual constructor bodies. So the body of the java.lang.Object constructor is executed first, then the direct subclass, etc. This is also when variable initializers are executed. (Prior to this, the variables have their default values of null etc.)
  • The reference is returned to whoever called new

默认构造函数的想法在执行时没有任何意义.就JVM而言,它只是一个调用 super()的无参数构造函数.

The idea of a default constructor has no meaning at execution time. It's just a parameterless constructor which calls super() as far as the JVM is concerned.

关于构造函数链的业务与如果它们是带有第一行的方法的方法完全相同,第一行只是将其链接到下一个构造函数;只是一堆电话.

The business about the constructor chain is exactly the same as it would be if these were methods with a first line which just chains to the next constructor along; it's just a stack of calls.

这篇关于这是Java中的构造方法分配内存的方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆