Copy Objects in Java:
We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it. |
In Java you can copy an object in several ways, among them, copy constructor is mostly used.
Copy Constructor: A copy constructor is simply a constructor that takes a single argument whose type is the class containing the constructor.
In Student.java class we define the objects and methods. We call these objects and methods in Main.java class as shown below.
Student.java Class:

public class Student {
private String stu_name;
private int stu_age;
private double stu_marks;
private String stu_city;
Student (String stu_name, int stu_age, double stu_marks, String stu_city){
this.setStudentName(stu_name);
this.setStudentAge(stu_age);
this.setStudentMarks(stu_marks);
this.setStudentCity(stu_city);
}
Student (Student x){
this.copy(x);
}
public String getStudentName() {
return stu_name;
}
public int getStudentAge() {
return stu_age;
}
public double getStudentMarks() {
return stu_marks;
}
public String getStudentCity() {
return stu_city;
}
public void setStudentName(String stu_name) {
this.stu_name = stu_name;
}
public void setStudentAge(int stu_age) {
this.stu_age = stu_age;
}
public void setStudentMarks(double stu_marks) {
this.stu_marks = stu_marks;
}
public void setStudentCity(String stu_city) {
this.stu_city = stu_city;
}
public void copy(Student x) {
this.setStudentName(x.getStudentName());
this.setStudentAge(x.getStudentAge());
this.setStudentMarks(x.getStudentMarks());
this.setStudentCity(x.getStudentCity());
}
}
Main.java Class:

public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student student1 = new Student("Andrew", 25, 91.50, "New York");
Student student2 = new Student(student1);
System.out.println(student1);
System.out.println(student2);
System.out.println();
System.out.println("Contents of the original object");
System.out.println(student1.getStudentName());
System.out.println("Age is " + student1.getStudentAge() + " years old");
System.out.println("Marks = " + student1.getStudentMarks());
System.out.println(student1.getStudentCity());
System.out.println();
System.out.println("Contents of the copied object");
System.out.println(student2.getStudentName());
System.out.println("Age is " + student2.getStudentAge() + " years old");
System.out.println("Marks = " + student2.getStudentMarks());
System.out.println(student2.getStudentCity());
}
}
Comments (No)