在 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
How do I build a copy constructor that receive another point (x,y) and copy its values ?
I decide a signature: public Point1 (Point1 other)
, but I don't know what to write in it...
The Point class looks like:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你的尝试
绝对没问题......(我已经更正了参数类型。)
我很想将
_x
和_y
最终,并使class Final,但那是因为我喜欢不可变类型。其他人肯定有不同的意见:)在继承层次结构上进行克隆有点棘手 - 层次结构中的每个类都必须有一个相关的构造函数,将其提供的任何参数传递给超类构造函数,然后仅复制其自己的字段。例如:
在实现方面这还不错,但如果您想忠实地克隆
Point2
,您需要知道它是以下位置的Point2
:为了调用正确的构造函数。实现
Cloneable
可以让这一切变得更简单,但是还有其他一些事情需要考虑......基本上克隆对象并不像看起来那么简单:)(我确信《Effective Java》中有相关条目,如果您没有,请立即购买。)Nope, your attempt of
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 :)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:
That's not too bad on the implementation side, but if you want to faithfully clone a
Point2
you need to know it's aPoint2
in order to call the right constructor.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.)虽然这个问题很老了,但这里有一个复制构造函数的例子
}
实现Clonable接口。
构造函数。
Although the question is quite old but here is an example of copy constructor
}
implement Clonable interface.
constructor.