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

查看:402
本文介绍了在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类看起来像: / p>

The Point class looks like:

public class Point1

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

}

我试过: b
$ b

I tried:

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

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

But I almost sure I can do it better..

thnx

推荐答案

不,你的尝试

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

是绝对精细...(我已更正参数类型。

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

我会试着让 _x _y 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.

实现可克隆允许这样做更简单一点,考虑周围...基本上克隆对象不是那么简单,它可能会出现:)(我敢肯定有效的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天全站免登陆