Building a copy constructor in Java

How to create a copy constructor that gets another point (x, y) and copy its values?

I decide the signature: public Point1 (Point1 other) , but I do not know what to write in it ...

The Point class looks like this:

 public class Point1 { private int _x , _y; public Point1 (Point1 other) { ... ... } //other more constructors here... } 

I tried:

 public Point1 (Point1 other) { _x = other._x ; _y = other._y; } 

But I'm pretty sure I can do it better.

Thnx

+7
source share
1 answer

No, your attempt

 public Point1(Point1 other) { _x = other._x ; _y = other._y; } 

absolutely normal ... (I adjusted the type of parameter.)

I will be tempted to make the endings _x and _y final and make the class final, but this is because I like immutable types. Others definitely have different opinions :)

Cloning the inheritance hierarchy is somewhat more complicated - each class in the hierarchy must have a corresponding constructor, pass any argument that it sets to the superclass constructor, and then copy only its own fields. For example:

 public class Point2 extends Point1 { private int _z; public Point2(Point2 other) { super(other); this._z = other._z; } } 

This is not so bad on the implementation side, but if you want to accurately clone Point2 , you need to know its Point2 in order to call the correct constructor.

Implementing Cloneable makes it a little easier, but there are other things to consider around ... basically cloning objects is not as easy as it might seem :) (I'm sure there is an entry in Effective Java for it. If you have no copy, buy it now.)

+16
source

All Articles