请帮助我消除这种困惑,它让我很烦恼。当我编写以下代码时,内存中会发生什么以及对象 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/