JavaIntermediate#oop#fundamentals

What is the difference between shallow copy and deep copy in Java?

A shallow copy duplicates an object's fields but for reference-type fields, copies only the reference (both objects share the same nested object). A deep copy recursively duplicates nested objects too, so the copies are fully independent.

Example
class Person implements Cloneable {
  List<String> hobbies;
  public Person clone() { 
    // shallow: shares hobbies list
    // deep would need: new ArrayList<>(hobbies)
  }
}

Related Questions

1
JavaAdvanced#oop#interface

What is the diamond problem and how does Java avoid it with interfaces?

Open
2
JavaIntermediate#serialization#keywords

What is the purpose of the transient keyword outside of serialization context — does it affect anything else?

Open
3
JavaIntermediate#interface#java8

What is the difference between an interface's default method and a static method?

Open