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 from another object. A copy constructor is a type of constructor that takes an object of the same class as an argument and creates a new object with the same properties as the original object.
Here is an example of a class with a copy constructor:
public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point other) { this.x = other.x; this.y = other.y; } // other methods go here }
To use the copy constructor, you can call it with an instance of the same class as an argument, like this:
Point p1 = new Point(1, 2);
Point p2 = new Point(p1);
The
p2
object will be a copy of the p1
object, with the same values for the x
and y
fields.
Comments
Post a Comment