gpt4 book ai didi

java - 在 Java 中构建复制构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:29 25 4
gpt4 key购买 nike

如何构建接收另一个点 (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;
}

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

谢谢

最佳答案

不,你的尝试

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

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

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

在继承层次结构上克隆有点棘手 - 层次结构中的每个类都必须有一个相关的构造函数,将它提供的任何参数传递给父类(super class)构造函数,然后只复制它自己的字段。例如:

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

这在实现方面还算不错,但是如果你想忠实地克隆一个 Point2,你需要知道它是一个 Point2以便调用正确的构造函数。

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

关于java - 在 Java 中构建复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5749218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com