简体   繁体   English

在方法中使用实例变量时的堆和堆栈(Java 内存)

[英]Heap and Stack when I use an instance variable in a method (Java Memory)

public class Main {
    private String sampleName= "Sample";
    public void show() {
        System.out.println(sampleName);
    }
}

I know "Sample" as a object locates in heap section, but Where is "sampleName" as a reference variable?我知道“样本”作为对象位于堆部分,但是“样本名称”作为参考变量在哪里? if it locates in heap, whether in stack I have another reference with name "sampleName" that reference to "sampleName" in heap ?如果它位于堆中,是否在堆栈中我有另一个名称为“sampleName”的引用,该引用引用了堆中的“sampleName”?

I know "Sample" as a object locates in heap section我知道“样本”作为一个对象位于堆部分

Correct.正确的。

but Where is "sampleName" as a reference variable?但是“sampleName”在哪里作为参考变量?

In the Main object, which by definition is in the heap.Main对象中,根据定义,它位于堆中。

if it locates in heap, whether in stack I have another reference with name "sampleName" that reference to "sampleName" in heap如果它位于堆中,则是否在堆栈中我有另一个名称为“sampleName”的引用,该引用引用了堆中的“sampleName”

Yes, as a temporary for the argument to println() .是的,作为println()参数的临时变量。

Your thread would only hold a reference to the enclosing Main object.您的线程将只持有对封闭Main对象的引用。 It points to the Main object allocated in the heap.它指向在堆中分配的Main对象。 The sampleName reference is a field of the Main object, hence also on the heap, pointing to the String "Sample" , which is maintained in the java constant String pool (another section in the heap). sampleName引用是Main对象的一个​​字段,因此也在堆上,指向 String "Sample" ,它在 java 常量字符串池(堆中的另一个部分)中维护。 There can't be a sampleName reference on the stack since it's a private field;堆栈上不能有sampleName引用,因为它是私有字段; otherwise, you would be able to access it in your code outside of the Main class, which is violating the java language semantics.否则,您将能够在Main类之外的代码中访问它,这违反了 Java 语言语义。 If you defined the sampleName field to be public , and in your code you did如果您将sampleName字段定义为public ,并且在您的代码中

Main main = new Main();
String copyOfSampleName = main.sampleName;

Then you would have a String reference on your stack that is pointing, together with the original sampleName reference, to the String object in the constant pool.然后,您的堆栈上将有一个String引用,该引用与原始sampleName引用一起指向常量池中的String对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM