gpt4 book ai didi

java - Java中的对象是如何创建的?具体来说,当一个对象被创建时,内存中发生了什么过程?

转载 作者:行者123 更新时间:2023-12-02 02:35:59 25 4
gpt4 key购买 nike

请帮助我消除这种困惑,它让我很烦恼。当我编写以下代码时,内存中会发生什么以及对象 Jhon 是如何存储的?(如果我是正确的,Jhon 是一个对象而不仅仅是对对象的引用)

class Human{
String Name;
float height;
}

class Student extends Human{
int Student_ID;
Student Jhon = new Student();
}

我的问题是,Jhon 是一个对象还是对创建的对象的引用?这里的引用变量是什么?这里的对象变量是什么?

最佳答案

我想说 the following line from JLS 很好地解释了这一点:

The value of a class instance creation expression is a reference to the newly created object of the specified class.

因此,在以下代码中:

Student Jhon = new Student();
^-----------^ Class instance creation expression
^----------^ Variable declaration

重申一下:类实例创建表达式的值是对新创建的对象引用。该对象是在内存中的某个位置创建的;但关键是该值不是该对象,而是对其的引用。

然后将该引用分配给变量Jhon。所以 Jhon 不是一个对象,也不是一个引用,而是一个变量,其值是对变量的引用。

关于java - Java中的对象是如何创建的?具体来说,当一个对象被创建时,内存中发生了什么过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46310430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com