Deep and Shallow Copy
public class shallow_deep {
public static void main(String[] args) {
Student s1= new Student();
s1.name="udit";
s1.rollno=44;
s1.marks[0]=100;
s1.marks[1]=200;
s1.marks[2]=300;
Student s2= new Student(s1);
s1.marks[2]=900;
s1.name="nikki";
System.out.println(s2.marks[2]+" "+s1.name);
}
}
class Student{
String name;
int rollno;
int marks[]=new int[3];
// Shallow Copy
// Student(Student s1){
// this.name=s1.name;
// this.rollno=s1.rollno;
// this.marks=s1.marks;
// }
// Deep Copy
Student(Student s1){
this.name=s1.name;
this.rollno=s1.rollno;
for(int i=0;i<marks.length;i++){
this.marks[i]=s1.marks[i];
}
}
Student(){
System.out.println("Default constructor is called");
}
}
Comments
Post a Comment