Forums Register Login

Passing Objects: I think I got it

+Pie Number of slices to send: Send
OK-

Someone please tell me if i am understanding this correctly. When we pass Object O to aMethod, both the local N and O are pointing to the same memory location. So, if we do an operation or call a method ON the local N, we will be also changing the value of O. But, once we say N = to something else (meaning a new memory location) then we will not be changing O. Is this correct?
Thanks-
Zac
+Pie Number of slices to send: Send
 

Originally posted by Zac Roberts:
OK-

Someone please tell me if i am understanding this correctly. When we pass Object O to aMethod, both the local N and O are pointing to the same memory location. So, if we do an operation or call a method ON the local N, we will be also changing the value of O. But, once we say N = to something else (meaning a new memory location) then we will not be changing O. Is this correct?
Thanks-
Zac


You've got it. Think about the activation stack. When you start the application, there is an activation record for main put onto the stack. In main, you declare an Object reference, o, and create a new object that it references.
Now, when you call aMethod, a new activation record is created on the stack. In that activation record, there is a new local variable, n. That local variable is populated with a reference to the same object that o references.
Now you have to variables that reference the same object. If you do anything to that object, it will be reflected by the other variable because they point to the same thing. However, if you assign a different reference to n, they will no longer reference the same object. That's why, in the method aMethod, you can affect the object referenced by o by manipulating the object referenced by n until you assign a new object reference to n.
If it helps, draw out the activation stack and see what's happening. Once you can visualize that stack, you'll never have problems with this again.
Corey
+Pie Number of slices to send: Send
Excellent, thanks...
Zac
keep an eye out for scorpions and black widows. But the tiny ads are safe.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 524 times.
Similar Threads
How come a super class method have a subclass object?
call by reference
Passing Object to a method
Type casting...Urgent ... Please help
marcus mock exam-- reference
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 05:14:37.