This is a technique that creates a copy of an existing object of the same class. In this example, first, an object c
is created. Later, we want to create another object cnew
which is nothing but a copy of the object c
. Here, the second constructor receives the object c
as a parameter and creates a new object cnew
.
ComplexNum.java
public class ComplexNum {
float x;
float y;
public ComplexNum(int x, int y) {
this.x = x;
this.y = y;
}
// copy constructor
public ComplexNum(ComplexNum ob) {
this.x = ob.x;
this.y = ob.y;
}
}
TestMain.java
public class TestMain {
public static void main(String[] args) {
ComplexNum c = new ComplexNum(10, 5);
// copy constructor call
ComplexNum cnew = new ComplexNum(c);
}
}
No comments:
Post a Comment