开发者

Building a copy constructor in Java

How do I build a copy constructor that receive ano开发者_如何学Cther 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


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

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 know it's a Point2 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.)


Although the question is quite old but here is an example of copy constructor

public class CopyConstructor {

private int id;
private String name;

public CopyConstructor(int id, String name) {
    super();
    this.id = id;
    this.name = name;
}

public CopyConstructor(CopyConstructor copy) {
    id = copy.id;
    name = copy.name;
}

}

  • Copy constructor is much easier to implement and we don't need to implement Clonable interface.
  • The clone method returns object which needs to cast , we don't need to cast copy constructor.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜