Copy Constructor in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.