Define Copy Constructor in Java
In Java, a copy constructor is a constructor that creates a new object by copying the values of the fields of an existing object. Copy constructors are used to create a new object with the same state as an existing object.
To create a copy constructor in Java, you need to define a constructor that takes an instance of the same class as an argument. This constructor should then copy the values of the fields of the argument object to the fields of the new object.
Here's an example of a class with a copy constructor:
public class Point { private int x; private int y; // regular constructor public Point(int x, int y) { this.x = x; this.y = y; } // copy constructor public Point(Point p) { this.x = p.x; this.y = p.y; } // getter and setter methods public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
In this example, the "Point" class has a copy constructor that takes a "Point" object as an argument and copies its fields to the fields of the new object.
To create a new "Point" object with the same state as an existing "Point" object, you can use the copy constructor like this:
Point p1 = new Point(1, 2); Point p2 = new Point(p1); // p2 is a copy of p1
Comments
Post a Comment