Clone Object using Java Program

Here I have shared, Simple program to write How to Clone Object using Java Program. The example program was tested and output is shared in the same post.

Student.java

The Student class which is implementing the java.lang.Cloneable interface. so that we can able to clone the student object.

package com.javatraineronline;
public class Student implements Cloneable {
private int studId;
private String studName;
public Student(int studId, String studName) {
this.studId = studId;
this.studName = studName;
}
public int getStudId() {
return studId;
}
public String getStudName() {
return studName;
}
public void getInformation() {
System.out.println("Studend ID : "+studId+" Student Name : "+studName);
}
public Object clone() {
try {
return super.clone(); // Cloning the Object
} catch (CloneNotSupportedException e) {
System.out.println(e.getMessage());
}
return null;
}
}

StudentCloneTest.java

package com.javatraineronline;
public class StudentCloneTest {
public static void main(String[] args) {
Student s1 = new Student(101, "John");
s1.getInformation();		
System.out.println("Reference Address : "+s1);
Student s2 = (Student)s1.clone();
s2.getInformation();
System.out.println("Reference Address : "+s2);
}
}

Output

—————–
Studend ID : 101 Student Name : John
Reference Address : com.javatraineronline.Student@8965fb
Studend ID : 101 Student Name : John
Reference Address : com.javatraineronline.Student@867e89

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *