Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java Copy Constructor

  • Copy constructor initializes an object using another object.
  • It receives an object as an argument.
  • Assign data of the object that received to an object that is created.

Example

class student {
      int rollno;
      String name;

      student(int r, String n) // constructor is defined, it has same name as class name 
      {
         rollno = r;
         name = n;
       }
     student(int r) // constructor is defined, it has same name as class name 
      {
         rollno = r;
         name = "Gargi";
       }
    student (student k) // copy constructor 
     {
        rollno = k.rollno;
	    name = k.name;
     }
     display ()
       {
           System.out.println ("roll no is " + rollno);
	   System.out.println ("name is "+ name);
	}
}

class demostudent {

   public static void main (String args[])
	{
      student s1 = new student(10, "Rajesh");  // two argument’s constructor will be called
     student s2 = new student(12)  // one argument constructor will be called

     student s3 = new student(s2); // copy constructor will be called

         s1.diaplay();
	 s2.display();
      }
}              

Explanation of the program

  • The program defines a class named 'student'.
  • Within the class 'student', three constructor are defined, it has same name as class name.
  • Constructor 'student (student k)' is called copy constructor. It receives a student object as an argument.
  • The class 'demostudent' is defined to create and access class 'student'.
  • The statement 'student s3 = new student(s2)' creates an object named s3. It calls copy constructor.
  • The above statement initializes object s3 using object s2.
  • The method display() is called by objects to display values of variables of objects.

Output of the program

roll no is 10
name is Rakesh
roll no is 12
name is Gargi
roll no is 12
name is Gargi


© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.