简体   繁体   中英

Object and reference to it in Java

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 ----> |----------------------|

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

是的,你是对的,选项1是正确的。

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.

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