您的位置:首页 > 编程语言 > Java开发

Copy Constructor in Java

2015-11-06 03:06 267 查看
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.

class Complex {

private double re, im;

// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}

// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}

// Overriding the toString of Object class
@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}

public class Main {

public static void main(String[] args) {
Complex c1 = new Complex(10, 15);

// Following involves a copy constructor call
Complex c2 = new Complex(c1);

// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
Complex c3 = c2;

System.out.println(c2); // toString() of c2 is called here
}
}


Output:

Copy constructor

called (10.0 + 15.0i)

class Complex {

private double re, im;

public Complex(double re, double im) {
this.re = re;
this.im = im;
}
}

public class Main {

public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
Complex c2 = new Complex(c1);  // compiler error here
}
}


Compile error
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: