开发者

Java reference storage question

In java, when you pass an object to a method as a parameter, it is actually passing a reference, or a pointer, to that object because objects in 开发者_StackOverflow社区Java are references.

Inside the function, it has a pointer to that object which is a location in memory. I am wondering where this pointer lives in memory? Is a new memory location created once inside the function to hold this reference?


Within a function, a parameter reference is stored on the stack. The thing-referenced can live anywhere.

When some code calls a method, what normally happens is that space is made on the executing thread's stack, and this space is used to hold the parameters that are passed to the function. If one of the parameters "is an object", what's really in play is a reference to an object; that reference is copied onto the stack so that the called code can find it. It's important to recognize that the object itself is not copied, just the reference.

The prologue section of the called code will then typically allocate more space on the stack, for the method's own local variables, but underneath, the JVM has a pointer to the stack frame with all the parameters, so the called code can locate the object named by the parameter. Items created with 'new' will be allocated from the heap, and can persist even after the method exits, but all items allocated on the stack are dumped simply by moving the stack pointer back to where it was before the call.


Objects are not references, but you use references everywhere. e.g.

String a = "abc";

the a is a reference to a String. So references get passed around everywhere. Are they pointers ? No. A reference is more like a handle to an object. The JVM is at liberty to move around objects within memory. A pointer would have to change to reflect this. A reference doesn't. A reference could be modelled as a pointer to a pointer.


Every parameter of the function is passed by value - however, the parameter is not an object, but instead is a reference.

So the same object exists with two references to it.

String s = "my string"; // reference to this object created
doSomething(s); // in the doSomething function, a new reference to the same point of memory is passed by value

This means when I have my function void doSomething(String str) I work the same way as I do outside the function, except I have a different reference. Same object being referenced, but different reference. So if inside my function I do str = "different string"; that won't change s - s still points to the same point of memory it did the whole time - but now str instead of pointing to what s points to, now points to where the "different string" is stored.


for example in JFrame you can start like this:

public myFrame mF;

public void Panel1(myFrame mF) {   your code ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜