OOPs HandbookObject Cloning (Shallow vs Deep Copy) & Composition vs Inheritance
ArchitectureIntermediate
8 min read

Object Cloning (Shallow vs Deep Copy) & Composition vs Inheritance

Why "favor composition over inheritance" is an industry mantra, and memory cloning differences.

TM
TestMeMan SDE Curriculum
Updated Sept 2026
Verified for FAANG Interviews
FROM TESTMEMAN•TestMeMan

Mock tests for SSC, Banking, Railways, UPSC & state exams

Real exam pattern, negative marking and a worked solution for every question.

Sponsored Publisher Placement•
ID: ad-top-leaderboard
Executive Summary

Object copying and relationships form the foundation of software design patterns and memory safety.

1. Shallow Copy vs Deep Copy#

Tricky Question 15 from the curriculum: "What is the difference between shallow copy and deep copy?"

• Shallow Copy: Copies only the references of objects, not the objects themselves. Both copies point to the same internal nested objects in memory! Mutating a nested object through one copy mutates both.

• Deep Copy: Creates an entirely new copy of the objects AND all their nested references recursively. Both objects are completely independent in memory.

1// Shallow Copy: address references shared
2Person p2 = p1.clone(); // If shallow, p2.address == p1.address
3
4// Deep Copy: address is cloned independently
5Person p2 = new Person(p1.getName(), new Address(p1.getAddress()));

2. Composition vs Inheritance ("has-a" vs "is-a")#

Tricky Question 9: "What is the difference between composition and inheritance?"

• Inheritance: Represents an "is-a" relationship (e.g., Car is-a Vehicle). Tightly couples the child class to the parent implementation.

• Composition: Represents a "has-a" relationship (e.g., Car has-an Engine). The outer class contains instances of other classes.

Senior SDE Rule: Favor Composition over Inheritance. Composition allows dynamic runtime swapping of components and avoids fragile base class hierarchies.

Sponsored ContentTestMeMan

Practise placement aptitude on the real test pattern

TCS NQT, Infosys, Wipro, Accenture and Cognizant style mocks with section-wise analysis.

Test Your Concept Mastery

Verify your retention on: Object Cloning (Shallow vs Deep Copy) & Composition vs Inheritance

Diagnostic Check
Question 1 of 1
A Car having an Engine represents which relationship?
Ready for a full proctored assessment?

Take a free quick test on the real exam pattern, with a worked solution for every question.

Launch Mock Test