簡體   English   中英

Java可復制對象,類似於此Python示例

[英]Java copiable objects, similar to this Python example

因此,這是我可以在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()方法。

您能想到解決方案嗎? 謝謝

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM