csb*_*sbl 3 java scope memory-management variable-types
我有以下代码块:
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
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题与什么是局部变量,实例变量有关,以便知道它们的分配位置,HEAP或STACK内存.在默认构造函数中,它似乎只存在一个Local变量,该变量由'this'关键字创建,但是如何'name ="Anonymous";' 不被认为是局部变量?这是对象类型,但那些也可以是局部变量,对吗?顺便提一下,您可以举例说明使用默认构造函数创建/实例化的对象吗?谢谢!
简而言之,任何类型的名称只存储引用,它们不直接存储对象.
完全受限于代码块的名称已在堆栈帧上为引用分配存储,该堆栈帧位于Thread专用的堆栈上.
作为类成员的名称已在Object中为表示该类实例的Object中的引用分配存储.
作为类的静态成员的名称已为堆中的引用分配存储,在Object中表示该类的Class对象的实例.
所有对象都存在于堆中; 但是,对它们的引用可能存在于堆上的其他对象中,或者存在于堆栈中的引用占位符中.
所有原始数据类型都存储在已存储引用的位置.
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
}
}
Run Code Online (Sandbox Code Playgroud)