如何克隆Interface定义的Object

时间:2014-04-19 21:44:55

标签: java android

我有一些不同的对象GoldPalladiumIron等。这些对象实现了Cloneable并且有一个名为Metal的公共接口。

在课堂上我收到一个金属,可能是金钯等,需要克隆这个

Public doSomething(Metal receivedMetal){
Metal dolly=//clone receivedMetal

dolly.doOperation();
replaceMetal(receivedMetal, dolly);
//replace use an indexOf on receivedMetal 
//and if I don't clone receivedMetal 
//doOperation edit also the original 
//receivedMetal and indexOf returns always -1
}

有没有办法克隆receivedMetal对象?

2 个答案:

答案 0 :(得分:0)

克隆可以通过创建一个构造函数来完成,该构造函数复制作为参数给出的对象中的所有字段。

public SomeObject(SomeObject o){

   this.someField = o.getSomeField();
   //etc..

}

- 编辑 -

您可以使用抽象类来定义您的克隆构造函数,而不是接口。那里。通过这种方式,您的子类可以覆盖它。

答案 1 :(得分:0)

如何在Metal中扩展Cloneable并向其中添加clone()?在下面的示例中,我看起来没问题(http://rextester.com/KCUGF81783):

import java.util.*;
import java.lang.*;

interface Metal extends Cloneable {
    public Metal clone();
}

class Iron implements Metal {

    public int val = 101;

    public Iron clone() {
        try {
            return (Iron) super.clone();
        } catch (CloneNotSupportedException e) {        
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public String toString() { return "Iron " + val; }
}

class Rextester
{  
    public static void main(String args[])
    {
        Metal metal = new Iron();
        Metal metal2 = metal.clone();

        ((Iron)metal).val = 200; // just to make sure metal2 is cloned

        System.out.println(metal2); // outputs: Iron 101
    }
}
相关问题