This is my final post on the discussion of copying objects efficiently in Java. I assume you have already gone through two of my previous articles - Default Copy Constructor in Java, Cloning to copy objects in Java. If not, it is advisable to go through those articles first to better understand this article.
Problems
Default Copy Constructor: Clearly new keyword is not polymorphic which renders code inextensible.
clone method: final fields are not mutable using clone method
Solution
Let’s try to combine both the methodologies to achieve our goal.
Result POJO
You can see that the aforementioned class still has the clone method but the implementation is a bit changed. Now, it is using it’s own Copy Constructor to create a whole new object.
ExcellentResult
This derived class also contains the clone method but the implementation uses its own Copy Constructor to create a new object by copying its contents.
Student POJO
Pretty much same as we did for Result and its derived ExcellentResult class.
Client Application
Benefits
Now, if we execute the aforementioned client application, we can see that the current implementation is conforming to our Deep Copy paradigm. Even though new is not polymorphic, at runtime the polymorphic clone method invokes the actual copy constructor on the runtime type of Result object.
Solution
Our approach should be to combine both the Copy Constructor and the clone method to deep copy an object in Java.