Here is 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(px, py); } }
Notice how the Point(Point p) constructor takes Point and makes a copy of it - a copy constructor .
This is a defensive copy because the original Point is protected from change by taking a copy of it.
So now:
Note that this is not necessarily the correct way to create objects. This, however, is a good way to create objects, which ensures that you never have two references to the same object by accident. Clearly, this is only good if that is what you want to achieve.
Oldcurmudgeon
source share