Cloning via a constructor

This cloning technique requires you to enrich the class with a constructor that takes a single argument representing an instance of the class that will be used to create the clone.

Let's see it in code:

public class Point {

private double x;
private double y;

public Point() {}

public Point(double x, double y) {
this.x = x;
this.y = y;
}

public Point(Point another) {
this.x = another.x;
this.y = another.y;
}

// getters and setters
}

Creating a clone can be done as follows:

Point point = new Point(...);
Point clone = new Point(point);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.61.170