用Java构建一个拷贝构造函数

如何构建一个接收另一个点(x,y)并复制其值的复制构造函数?

我决定签名: public Point1 (Point1 other) ,但我不知道写什么…

Point类看起来像:

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

我试过了:

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

但我几乎可以肯定我能做得更好..

日Thnx

不,你的尝试

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

绝对没问题…(我已经更正了参数类型。)

我很想做_x_y final,并让这个类最终,但那是因为我喜欢不可变类型。 其他人肯定有不同的意见:)

在inheritance层次结构上进行克隆有点棘手 – 层次结构中的每个类都必须有一个相关的构造函数,传递它给予超类构造函数的任何参数,然后只复制它自己的字段。 例如:

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

这在实现方面并不算太糟糕,但如果你想忠实地克隆一个Point2你需要知道它是一个Point2才能调用正确的构造函数。

实现Cloneable可以让它更简单地完成,但还有其他事情要考虑……基本上克隆对象并不像看起来那么简单:)(我确信在Effective Java中有一个条目如果您没有副本,请立即购买。)