Java可复制对象,类似于这个Python示例

时间:2012-11-21 09:52:35

标签: java python copy cloning

所以,这就是我在Python中可以做的事情:

class Copiable(object):

    def copy_from(self, other):
        """ This method must be implemented by subclasses to define their
            own copy-behaviour. Never forget to call the super-method. """

        pass

    def copy(self):
        """ Creates a new copy of the object the method is called with. """

        instance = self.__new__(self.__class__)
        instance.copy_from(self)
        return instance

class Rectangle(Copiable):

    def __init__(self, x, y, w, h):
        super(Rectangle, self).__init__()
        self.x = x
        self.y = y
        self.w = w
        self.h = h

  # Copiable

    def copy_from(self, other):
        self.x = other.x
        self.y = other.y
        self.w = other.w
        self.h = other.h
        super(Rectangle, self).copy_from(self)

我在Java版本中面临两个问题:

  • 我不知道如何创建类似于Python的__new__方法的类的实例。
  • 我希望Copiable成为一个界面,但是,我无法实现clone()方法。

你能想到一个解决方案吗?感谢

1 个答案:

答案 0 :(得分:0)

Java使用new关键字来构造对象。创建Copiable接口不应干扰clone()方法。

public interface Copiable<T> {
    public T copy();
    public T copyFrom(T other);
}

public class Rectangle implements Copiable<Rectangle> {

    private int x, y, w, h;

    @Override
    public Rectangle copy() {
        return new Rectangle();
    }

    @Override
    public Rectangle copyFrom(Rectangle other) {
        return new Rectangle(other);
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getW() {
        return w;
    }

    public int getH() {
        return h;
    }

    public Rectangle() {}
    public Rectangle(Rectangle other) {
        this.x = other.getX();
        this.y = other.getY();
        this.w = other.getW();
        this.h = other.getH();
    }
}