How to copy objects in Java: Shallow copy and deep copy
Copying objects is a common operation in enterprise projects. When copying an object, we must ensure that we end up with a new instance that holds the values we want.
Domain objects are usually complex. Making a copy with the root object and composed objects is also not trivial.
Let's explore the most effective ways to copy an object using shallow and deep copy techniques.
Object references
To correctly perform a shallow or deep object copy, we must first know what not to do. Understanding object references is essential for using shallow and deep copy techniques.
When making a copy of an object, it is important to avoid using the same object reference. It's an easy mistake, as this example shows. To start, here's the Product object we'll use in our examples: