在 Java 中构建复制构造函数 [英] Building a copy constructor in Java

查看:35
本文介绍了在 Java 中构建复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I build a copy constructor that receive another point (x,y) and copy its values ?

我决定了一个签名:public Point1 (Point1 other) ,但我不知道在里面写什么...

I decide a signature: public Point1 (Point1 other) , but I don't know what to write in it...

Point 类看起来像:

The Point class looks like:

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;
}

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

But I almost sure I can do it better..

谢谢

推荐答案

不,你的尝试

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

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

is absolutely fine... (I've corrected the parameter type.)

我很想将 _x_y 设为 final,并将类设为 final,但那是因为我喜欢不可变类型.其他人肯定有不同的意见:)

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:

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

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

That's not too bad on the implementation side, but if you want to faithfully clone a Point2 you need to know it's a Point2 in order to call the right constructor.

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

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.)

这篇关于在 Java 中构建复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆