What is object cloning?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for OOP Concepts development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Object cloning creates a copy of an existing object. Two types with very different semantics: Shallow copy: creates a new object with the same field values. Primitive fields are copied by value. Reference fields — only the reference is copied (both original and copy point to the SAME nested objects): class Address { String city; String street; } class Person { String name; Address address; } Person original = new Person(); original.name = "Alice"; original.address = new Address("New York", "5th Ave"); // Shallow copy: Person copy = (Person) original.clone(); // Works if Person implements Cloneable copy.name = "Bob"; // Fine -- primitives/Strings are independent original.name; // Still "Alice" copy.address.city = "London"; // Danger! original.address.city; // Also "London"! Same Address object!. Deep copy: creates a new object AND recursively copies all nested objects — fully independent: class Person implements Cloneable { String name; Address address; @Override protected Person clone() throws CloneNotSupportedException { Person cloned = (Person) super.clone(); // Deep copy of address: cloned.address = new Address(this.address.city, this.address.street); return cloned; } } // Alternatively, deep copy via serialization or copy constructor.. Java Cloneable interface: marker interface — must be implemented for clone() to work; calling clone() on a non-Cloneable object throws CloneNotSupportedException. Many consider Java's Cloneable design flawed (effective Java recommends copy constructors or static factories instead). Copy constructor (preferred): public Person(Person other) { this.name = other.name; this.address = new Address(other.address); }.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a OOP Concepts codebase.