Created
June 8, 2019 07:18
-
-
Save Arkango/af5e2db95bac9d75ed89f703ffa4977d to your computer and use it in GitHub Desktop.
In the above example, ‘student1‘ is an object of ‘Student‘ class which has three fields – id, name and course. ‘course‘ is a reference variable pointing to a ‘Course‘ type object. Clone of ‘student1‘ is created by calling clone method on it and assigned it to ‘student2‘. As default version of clone method creates the shallow copy, the ‘course‘ f…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Course | |
{ | |
String subject1; | |
String subject2; | |
String subject3; | |
public Course(String sub1, String sub2, String sub3) | |
{ | |
this.subject1 = sub1; | |
this.subject2 = sub2; | |
this.subject3 = sub3; | |
} | |
} | |
class Student implements Cloneable | |
{ | |
int id; | |
String name; | |
Course course; | |
public Student(int id, String name, Course course) | |
{ | |
this.id = id; | |
this.name = name; | |
this.course = course; | |
} | |
//Default version of clone() method. It creates shallow copy of an object. | |
protected Object clone() throws CloneNotSupportedException | |
{ | |
return super.clone(); | |
} | |
} | |
public class ShallowCopyInJava | |
{ | |
public static void main(String[] args) | |
{ | |
Course science = new Course("Physics", "Chemistry", "Biology"); | |
Student student1 = new Student(111, "John", science); | |
Student student2 = null; | |
try | |
{ | |
//Creating a clone of student1 and assigning it to student2 | |
student2 = (Student) student1.clone(); | |
} | |
catch (CloneNotSupportedException e) | |
{ | |
e.printStackTrace(); | |
} | |
//Printing the subject3 of 'student1' | |
System.out.println(student1.course.subject3); //Output : Biology | |
//Changing the subject3 of 'student2' | |
student2.course.subject3 = "Maths"; | |
//This change will be reflected in original student 'student1' | |
System.out.println(student1.course.subject3); //Output : Maths | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment