WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Software Engineering · Intermediate · question 23 of 100

Explain the difference between a shallow copy and a deep copy in object cloning.?

📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

In object-oriented programming, object cloning is the process of creating a copy of an object. There are two main types of object cloning: shallow copy and deep copy.

A shallow copy creates a new object and fills it with references to the same child objects as the original object. In other words, the newly created object shares the references to its child objects with the original object, rather than creating new child objects for each.

In contrast, a deep copy creates a new object and fills it with copies of the child objects of the original object. In this case, the newly created object does not share any references to its child objects with the original object, but rather has its own separate child objects.

For example, consider a simple class hierarchy with a parent class ‘Person‘ and a child class ‘Student‘, which inherits from ‘Person‘. The ‘Person‘ class has two properties, ‘name‘ and ‘age‘, while the ‘Student‘ class has an additional property, ‘school‘.

Now suppose we create an instance of the ‘Student‘ class and clone it using a shallow copy:

Student s1 = new Student("John", 18, "High School");
Student s2 = s1.cloneShallow();

If we modify the ‘school‘ property of ‘s1‘, it will also be changed in ‘s2‘ because they both reference the same ‘school‘ object:

s1.setSchool("College");
System.out.println(s2.getSchool()); // "College"

On the other hand, if we clone ‘s1‘ using a deep copy, any changes made to the ‘school‘ property of ‘s1‘ will not affect ‘s2‘ because they have separate ‘school‘ objects:

Student s3 = s1.cloneDeep();
s1.setSchool("College");
System.out.println(s3.getSchool()); // "High School"

In general, shallow copy is faster and more memory-efficient, but it may lead to unexpected side effects if the child objects are modified. Deep copy is safer but more expensive in terms of performance and memory usage. The choice between shallow and deep copy depends on the specific requirements of the application.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Software Engineering interview — then scores it.
📞 Practice Software Engineering — free 15 min
📕 Buy this interview preparation book: 100 Software Engineering questions & answers — PDF + EPUB for $5

All 100 Software Engineering questions · All topics