gpt4 book ai didi

java - 局部变量、对象引用及其内存分配

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:18 26 4
gpt4 key购买 nike

我有以下代码块:

class Student{

int age; //instance variable
String name; //instance variable

public Student()
{
this.age = 0;
name = "Anonymous";
}
public Student(int Age, String Name)
{
this. age = Age;
setName(Name);
}
public void setName(String Name)
{
this.name = Name;
}
}

public class Main{
public static void main(String[] args) {
Student s; //local variable
s = new Student(23,"Jonh");
int noStudents = 1; //local variable
}
}

我的问题与什么是局部变量、实例变量有关,以便了解它们的分配位置,无论是在 HEAP 还是 STACK 内存中。在默认构造函数中,它似乎只存在一个局部变量,即由“this”关键字创建的那个,但是怎么来的'name =“Anonymous”;'不被认为是局部变量?它是 Object 类型,但那些也可以是局部变量,对吗?顺便说一句,你能举一个用默认构造函数创建/实例化的对象的例子吗?谢谢!

最佳答案

简而言之,任何类型的名称都只存储引用,它们不直接存储对象。

完全受限于代码块的名称已在堆栈帧上为引用分配了存储空间,堆栈帧位于线程私有(private)的堆栈上。

作为类成员的名称已在表示该类实例的对象内为堆中的引用分配了存储空间。

作为类的静态成员的名称已为堆中的引用分配了存储空间,在表示该类的类对象实例的对象中。

所有对象都在堆上;但是,对它们的引用可能存在于堆上的其他对象中,或者存在于堆栈上的引用占位符中。

所有原始数据类型都存储在本应存储引用的位置。

class Student {

int age; // value stored on heap within instance of Student
String name; // reference stored on heap within instance of Student

public Student() {
this.age = 0;
name = "Anonymous";
}

public Student(int Age, String Name) {
this.age = Age;
setName(Name);
}

public void setName(String Name) {
this.name = Name;
}

}

public class Main {
public static void main(String[] args) {
Student s; // reference reserved on stack
s = new Student(23, "John"); // reference stored on stack, object allocated on heap
int noStudents = 1; // value stored on stack
}
}

关于java - 局部变量、对象引用及其内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658111/

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