1

我想问你如何将 firstClass 对象复制到 secondClass 对象?

这可以通过使用clone()来解决吗?

情况如下所示:

我有一个类 fx firstClass。而且我需要将 firstClass 对象克隆为 secondClass 对象(并且这些克隆的对象必须存储到数组中)

谢谢

编辑:

抱歉有点信息。但我的任务是这样的:

编写一个 Garage 类,其对象可以在一个数组中容纳多达一定数量的 Vehicle 对象。将 Garage 设为 Cloneable 类型,并为其编写适当的克隆方法。编写一个 Garage.main 方法来测试它。

4

3 回答 3

3

按照惯例,Object.clone()方法及其覆盖应始终返回原始类型的对象。

x.clone().getClass() == x.getClass()

clone()因此,如果正确实施和使用,应该不可能创建不同类型的对象。

于 2013-10-21T18:27:13.747 回答
3

这不是克隆。如果你有两个不相关的类,你能做的最好的就是为 SecondClass 编写一个构造函数,它将 FirstClass 对象作为参数并将所有值写入适当的字段:

public SecondClass (FirstClass source){
  this.valueA = source.getValueA();
  this.valueB = source.getBValue();
  this.valueC = source.getProperCValue();
  ...
}
于 2013-10-21T18:29:22.557 回答
1

像这样的东西?!

class Foo{
  private String bar;
  public Object clone(){
    Foo f=new Foo();
    f.setBar(this.bar);
    //filling and copy the f attributes
    guys.add(f);
  }
   ///
   private final static List<Foo> guys=new ArrayList<>();
   ///
}
于 2013-10-21T18:32:19.000 回答