Reference:tutorialpoints, Geekforgeeks
The copy constructor is a constructor which creates an object by initializing it with an object of the same class , which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
In C + +, if a copy constructor is not defined in a class, the compiler itself defines one.
Java also supports copy constructor. But, unlike C + +, Java doesn ' t create a default copy constructor if you don ' t write your own.
1 classComplex {2 3 Private DoubleRe, im;4 5 //A normal parametrized constructor6 PublicComplex (DoubleReDoubleim) {7 This. Re =re;8 This. im =im;9 }Ten One //copy Constructor A Complex (Complex c) { -System.out.println ("Copy constructor called"); -Re =c.re; theim =c.im; - } - - //overriding the toString of Object class + @Override - PublicString toString () { + return"(" + Re + "+" + im + "i)"; A } at } - - Public classMain { - - Public Static voidMain (string[] args) { -Complex C1 =NewComplex (10, 15); in - //following involves a copy constructor call toComplex C2 =NewComplex (C1); + - //Note that following doesn ' t involve a copy constructor call as the //non-primitive variables is just references. *Complex C3 =C2; $ Panax NotoginsengSystem.out.println (C2);//toString () of C2 is called here - } the}
Output:
Copy Constructor
Called (10.0 + 15.0i)
1 classComplex {2 3 Private DoubleRe, im;4 5 PublicComplex (DoubleReDoubleim) {6 This. Re =re;7 This. im =im;8 }9 }Ten One Public classMain { A - Public Static voidMain (string[] args) { -Complex C1 =NewComplex (10, 15); theComplex C2 =NewComplex (C1);//Compiler Error here - } -}
Compile Error
Copy Constructor in Java