Copy constructor in Java
In this tutorial, we are gonna learn about copy constructor in Java. Firstly we are gonna know what is a constructor. A constructor is a block of code that is used to initialize an object. The constructor is having the same name as that of the class with no return type. For example: –
Code: –
class Student{ String name; int rollno; int classno; Student(String name,int rollno,int classno){//This is a constructor this.name=name; this.rollno=rollno; this.classno=classno; } } public class Main { public static void main(String[] args) { Student s1=new Student("Adi",1,12); //We initialised the name as "Adi", the rollno as 1 and the classno as 12 String s=s1.name; System.out.println(s); } }
Code Output: –
Adi
Now we will see initialization of more than two objects: –
class Student{ String name; int rollno; int classno; Student(String name,int rollno,int classno){ this.name=name; this.rollno=rollno; this.classno=classno; } } public class Main { public static void main(String[] args) { Student s1=new Student("Adi",1,12); Student s2=new Student("Ama",2,13); Student s3=new Student("Adi",1,12); Student s4=new Student("Qwe",4,15); String sname1=s1.name; String sname2=s2.name; String sname3=s3.name; String sname4=s4.name; System.out.println(sname1+" "+sname2+" "+sname3+" "+sname4); } }
Code Output: –
Adi Ama Adi Qwe
Here we see that we have to write a lot of times the same thing, for example, s1 and s3 are having the same values. This increases the redundancy in the code so to decrease this we use Copy constructor.
Copy Constructor Example
This is used to initialize an object using the object of the same class. In Java, we have to define this constructor explicitly whereas in C++ it is created by default.
Code: –
class Student{ String name; int rollno; int classno; Student(String name,int rollno,int classno){//This is general constructor this.name=name; this.rollno=rollno; this.classno=classno; } Student(Student s){//This is a copy constructor this.name=s.name; this.rollno=s.rollno; this.classno=s.classno; } } public class Main { public static void main(String[] args) { Student s1=new Student("Adi",1,12); Student s2=new Student("Ama",2,13); Student s3=new Student(s1);//This copies the content of s1 Student s4=new Student(s2);//This copies the content of s2 String sname1=s1.name; String sname2=s2.name; String sname3=s3.name; String sname4=s4.name; System.out.println(sname1+" "+sname2+" "+sname3+" "+sname4); } }
Code Output: –
Adi Ama Adi Ama
In this we saw that we did not have to write the values of s1 and s2 repeatedly we just used the s1 and s2 inside the constructor to get all of its value. This is how a copy constructor works.
Also read: –
Leave a Reply