讓我們來看看Java中會發生什麼。
// Create a new Person object
// and let the variable objperson1 refer to it
Person objperson1 = new Person();
// Call the method setAge(int) on the object previously created
objperson1.setAge(30);
// Create another Person object
// and let the variable objperson2 refer to it
Person objperson2 = new Person();
// Let the variable objperson2 refer to the object objperson1
// is referring to.
// The reference to the Person objperson2 was referring to
// HAS NO LONGER A REFERENCE TO IT. You can never reach that object again.
objperson2 = objperson1;
// Setting the age on objperson1 reflects a change in objperson2, because
// they refer to the very same object
objperson1.setAge(40);
這裏的誤解是什麼propably你認爲var1 = var2
實際上克隆是什麼。
有一種方法克隆你的對象,如this answer所述。
但問題是你是否需要克隆兩個對象。你可以創建兩個對象是這樣的:
Person alan = new Person(30);
Person boris = new Person(30);
boris.setAge(40);
PS:使用clone()
和實施Cloneable
接口爲discouraged in Effective Java。
嘗試克隆對象 –
'objperson2 = objperson1;' - 現在你不再有兩個對象,但只有一個。 –
實現可複製的界面 – Lokesh