Copy constructors and defensive copying

Here’s a good example:

class Point {
  final int x;
  final int y;

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

  Point(Point p) {
    this(p.x, p.y);
  }

}

Note how the constructor Point(Point p) takes a Point and makes a copy of it – that’s a copy constructor.

This is a defensive copy because the original Point is protected from change by taking a copy of it.

So now:

// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

Note that this is not necessarily the correct way of creating objects. It is, however, a good way of creating objects that ensures that you never have two references to the same object by accident. Clearly this is only a good thing if that is what you want to achieve.

Leave a Comment