Reputation: 2718
I came accross this article:
http://www.informit.com/articles/article.aspx?p=174371&seqNum=4
and I do not think it is correct picture used to show references to object if I create variables in such way:
pt1 = new Point(100,100)
pt2 = new Point(100,100)
My question is:
which situation takes place if I create two points as above, how the references to object/objects looks like? (I assume Option 1 is correct):
Option1:
pt1 ---->[Point object: 100, 100]
pt2 ---->[Point object: 100, 100]
Option2:
pt1 ----> |----------------------|
|Point object: 100, 100|
pt2 ----> |----------------------|
Upvotes: 1
Views: 93
Reputation: 45826
Just to point out why only option 1 can be correct: think about what the consequences would be if option 2 was correct:
pt1 = new Point(100,100)
pt2 = new Point(100,100)
pt1.x = 200
System.out.println(pt2.x)
What would that print?
If references to similar objects automatically pointed to the same memory, modifying one would modify the other, but only in situations where a similar object is created. That would be surprising behavior to say the least.
It should be noted though that in languages that emphasise immutability, option 2 is possible, since you have a guarantee that the object will never change.
Upvotes: 0
Reputation: 2189
If you say:
pt1 = new Point(100,100)
pt2 = new Point(100,100)
then option 1 is correct.
If you say:
pt1 = new Point(100,100)
pt2 = pt1
then option 2 occurs
Upvotes: 3