Shallow and Deep Copy example
This commit is contained in:
parent
966d488013
commit
183e213f0e
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user