Shallow and Deep Copy example

This commit is contained in:
Neetika Khandelwal 2023-08-10 23:11:25 +05:30
parent 966d488013
commit 183e213f0e
2 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package com.baeldung.shallowdeepcopy;
class Student {
private String name;
private int rollno;
public Student(String name, int rollno) {
this.name = name;
this.rollno = rollno;
}
public String getName() {
return name;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.shallowdeepcopy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class ShallowDeepCopyExampleTest {
@Test
void testShallowCopy() {
Student originalStudent = new Student("John", 20);
Student shallowCopy = originalStudent;
shallowCopy.setName("Baeldung");
shallowCopy.setRollno(10);
assertEquals("Baeldung", originalStudent.getName());
assertEquals(10, originalStudent.getRollno());
}
@Test
void testDeepCopy() {
Student originalStudent = new Student("John", 20);
Student deepCopy = new Student(originalStudent.getName(), originalStudent.getRollno());
deepCopy.setName("Baeldung");
deepCopy.setRollno(10);
assertEquals("John", originalStudent.getName());
assertEquals(20, originalStudent.getRollno());
assertEquals("Baeldung", deepCopy.getName());
assertEquals(10, deepCopy.getRollno());
}
}