oop
24. Shallow vs Deep Copy: Cloning & OOP
Analyze the code, write your predicted output, and then reveal the solution.
The Scenario
Object duplication is a key concept in OOP. If an object contains references to other objects, simply copying the reference leads to a "Shallow Copy".
class Engine { String type = "V8"; } class Car implements Cloneable { Engine engine = new Engine(); public Object clone() throws CloneNotSupportedException { return super.clone(); // Default behavior } } public class Main { public static void main(String[] args) throws Exception { Car car1 = new Car(); Car car2 = (Car) car1.clone(); car2.engine.type = "V12"; System.out.println("Car 1 Engine: " + car1.engine.type); System.out.println("Car 2 Engine: " + car2.engine.type); System.out.println("Same Engine Object? " + (car1.engine == car2.engine)); } }
Take Your Shot
Predicted Output
Type exactly what you think will be printed in the console.