简体   繁体   中英

In Java, what does object variable reference point to?

I see that an array reference points at the memory address of array[0]. What does the memory address of an object variable point to? ie Car c1 = new Car("Chevy", "Tahoe");

Thought maybe it points to the first instance variable but that doesnt make sense b/c can have classes w/o instance variables.

What does the memory address of an object variable point to?

An object is just a chunk of memory. In a typical implementation of Java, that chunk is part of a larger range of memory known as the heap.

Exactly what makes up the structure of the object, its particular bits and bytes is of no concern to us regular Java programmers. How the structure of an object is laid out in memory is an implementation detail that does not concern us.

ie Car c1 = new Car("Chevy", "Tahoe");

Two steps involved here.

The right side of the assignment = instantiates the object. This means a chunk of memory in the heap is located. The values passed to the constructor are written into member fields in that memory.

The left side of the assignment = takes the location of that newly created object and assigns it to the variable named c1 . If c1 is a local variable, it lives in the stack , in a typical implementation of Java.

In Java we never see the actual memory address. In code such as c1.model , we trust the JVM will find the c1 var on the stack, use its internally-maintained memory address to access the particular Car object, then navigate within that object's allocated chunk of memory to retrieve the value of the member field named model .

堆栈中的引用变量通向位于堆中的对象的示意图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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