'Don't think I'm getting .clone()
Let's say I have a class called House with two fields:
- int area
- java.util.Date whenBuilt
I would like to perform a deep copy of this class using clone() by overriding the clone method in the Object class:
public Object clone() throws CloneNotSupportedException {
// Perform a shallow copy
House houseClone = (House)super.clone();
// Deep copy on whenBuilt
houseClone.whenBuilt = (java.util.Date)(whenBuilt.clone());
return houseClone;
}
Apparently the code above is how this should be done. What I don't understand is this: Doesn't writing whenBuilt.clone() do a shallow copy of the Date object and not a deep copy? In other words, wouldn't my houseClone's whenBuilt field still refer to my original House class and its whenBuilt field? My understanding is that all clone methods, by default, don't do deep copies. What am I not getting?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
