In Java all variables are passed by value. For objects, this means that we pass reference on object. I am confused with following situation. Let's say that we have a graph of objects. One object contains as field reference to another object, that object has reference to one more object like: user.address.city. Here we have instance of class User, that instance has reference to instance of class Address which has field of type String - city. Now let's say we have 2 users:
User bob = new User(); User mary = new User(); Assume object 'bob' has reference to address object:
Address bobAddress = new Address(); bobAddress.setCity("New York"); bob.setAddress(bobAddress); Let's say Mary and Bob started to live together in one house and they have the same address, no problem:
mary.setAddress(bobAddress); Now mary and bob have reference to one address object. But one day they divorced and mary now has another address:
mary.getAddress().setCity("Boston"); And here we have a problem: Mary changed something in her address, but she also changed Bob's address, because they share the same reference.
All text above was my try to describe in small scale a big problem for me: When I should create a copy (clone) of some object before set the reference of that object into another instance? Does some rules or techniques exist? I know about immutable objects (e.g. String, Integer ...) with these objects we don't need to think about such problems at all, but what if I have mutable objects. How I should behave with them?