Re: Pointer vs Reference
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Sun, 30 Sep 2007 12:27:17 -0400
Erik Wikström wrote:
Foo f1 = new Foo();
Foo f2 = f1;
While it does not exactly take the address of the object referred to by
f1, it does create a new reference (pointer) that points to the same object.
Roedy Green wrote:
In assembler, what that does in allocate space for a new Foo object on
the heap somewhere. It puts the 32-bit address of that object in f1, a
local variable allocated on the stack frame.
Then it copies the pointer value from f1 and stores it in f2.
No reference is created, except on the initial allocation.
Oh, I see, I was under the impression that f1 was a reference. Just out
f1, f2 are variables that hold references.
of curiosity what is a reference in Java? Does f1 (and later f2) point
to a reference which refers to the Foo object, or is the Foo object the
reference (which would be quite counter intuitive)?
A reference is a pointer is a reference is a pointer ... in Java. A reference variable holds a reference, which is a "magic arrow that points to a thing", in some sense an address of that thing (that does not translate to a unique number unchanged over the lifetime of the object). Whether you think of f1 and f2 as two magic arrows that look exactly the same and point to the same thing, or as two variables that hold copies of the exact same magic arrow that points to a thing is a matter of conceptual approximation and your choice.
If you have two pieces of paper that have printed on them, "123 Main Strasse, Gewürtztraminer, Bavaria", is that two pieces of paper that hold the same address (reference), or that hold two copies of the same address?
Was a new reference created when the contents of one piece of paper were copied to the other? Certainly no new address was created, in the sense that the location is the same in both cases. If you think of the "reference" as the information in the variable, you could argue that it's not a different reference but the same reference in a different variable.
"piece of paper" -> "variable"
"123 Main Strasse,..." -> "reference" or "pointer"
"the Led Zeppelin residence" -> "object"
--
Lew
.
- References:
- Re: Pointer vs Reference
- From: Erik Wikström
- Re: Pointer vs Reference
- Prev by Date: Re: data transport
- Next by Date: Re: Great SWT Program
- Previous by thread: Re: Pointer vs Reference
- Next by thread: generics and arrays and multi-class collections
- Index(es):
Relevant Pages
|