在 Java 中构建复制构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5749218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Building a copy constructor in Java
提问by Master C
How do I build a copy constructor that receive another point (x,y) and copy its values ?
如何构建接收另一个点 (x,y) 并复制其值的复制构造函数?
I decide a signature: public Point1 (Point1 other)
, but I don't know what to write in it...
我决定签名:public Point1 (Point1 other)
,但我不知道在上面写什么...
The Point class looks like:
Point 类看起来像:
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 almost sure I can do it better..
但我几乎可以肯定我可以做得更好..
thnx
谢谢
回答by Jon Skeet
Nope, your attempt of
不,你的尝试
public Point1(Point1 other)
{
_x = other._x ;
_y = other._y;
}
is absolutely fine... (I've corrected the parameter type.)
绝对没问题......(我已经更正了参数类型。)
I'd be tempted to make _x
and _y
final, and make the class final, but that's because I like immutable types. Others definitely have different opinions :)
我很想 make_x
和_y
final,并使类成为 final,但那是因为我喜欢不可变类型。其他人肯定有不同的意见:)
Cloning on an inheritance hierarchy is slightly trickier - each class in the hierarchy has to have a relevant constructor, pass whatever argument it's given to the superclass constructor, and then copy just its own fields. For example:
在继承层次结构上克隆稍微有点棘手——层次结构中的每个类都必须有一个相关的构造函数,将它提供的任何参数传递给超类构造函数,然后只复制它自己的字段。例如:
public class Point2 extends Point1
{
private int _z;
public Point2(Point2 other)
{
super(other);
this._z = other._z;
}
}
That's not too bad on the implementation side, but if you want to faithfully clone a Point2
you need to knowit's a Point2
in order to call the right constructor.
这在实现方面还不错,但是如果您想忠实地克隆 a Point2
,则需要知道它是 aPoint2
以便调用正确的构造函数。
Implementing Cloneable
allows this to be done a bit more simply, but there are other things to consider around that... basically cloning objects isn't as simple as it might appear :) (I'm sure there's an entry in Effective Java for it. If you don't have a copy, buy one now.)
实现Cloneable
允许更简单地完成这一点,但还有其他事情需要考虑......基本上克隆对象并不像看起来那么简单:)(我确定在 Effective Java 中有一个条目) .如果您没有副本,请立即购买。)