2

I have a base class, say Base which specifies the abstract method deepCopy, and a myriad of subclasses, say A, B, C, ... Z. How can I define deepCopy so that its signature is public X deepCopy() for each class X?

Right, now, I have:

abstract class Base {
  public abstract Base deepCopy();
}

Unfortunately, that means that if if I have an object from a subclass, say a of A, then I always have to perform an unchecked cast for a more specific deep copy:

A aCopy = (A) a.deepCopy();

Is there a way, perhaps using generics, to avoid casting? I want to guarantee that any deep copy returns an object of the same runtime class.

Edit: Let me extend my answer as covariant typing isn't enough. Say, I then wanted to implement a method like:

static <N extends Base> List<N> copyNodes(List<N> nodes) {
    List<N> list = Lists.newArrayList();
    for (N node : nodes) {
      @SuppressWarnings("unchecked")
      N copy = (N) node.deepCopy();
      list.add(copy);
    }
    return list;
  }

How could I avoid the unchecked warning?

4

3 回答 3

5

Java 5 supports covariant return types which means that you can implement your deepCopy() method in each subclass to return the specific sub-class instance; e.g.

public class Z extends Base {
  @Override
  public Z deepCopy() {

  }
}

More on covariant return types here.

于 2009-09-03T21:57:46.207 回答
2

这真的不漂亮,我可能不会自己做,但是:

    public abstract class Base<T extends Base<T>> {
    public abstract T deepCopy();
}
public class Extender extends Base<Extender> {

    @Override
    public Extender deepCopy() {
        // TODO Auto-generated method stub
        return null;
    }
}

或者....

    public abstract class Base<T extends Base<T>> {
    public abstract T deepCopy();
}
public class Extender<T extends Base<T>> extends Base<T> {

    @Override
    public T deepCopy() {
        // TODO Auto-generated method stub
        return null;
    }
}
于 2009-09-04T08:41:34.757 回答
1

怎么样...

public interface DeeplyCloneable <T extends Cloneable> {
    public T deepClone();
}

然后......例如......(有错误,但善意;帮助!)

public class DeeplyClonableHashTable

         <T1 extends DeeplyCloneable<?>,T2 extends DeeplyCloneable<?>> 
extends Hashtable<T1,T2>
implements DeeplyCloneable<Hashtable<T1,T2>>{

@Override
public Hashtable<T1, T2> deepClone() {
  Object o = super.clone();
  if ((o == null) || (! (o instanceof DeeplyClonableHashTable<?,?>)))
  {
    throw new DeepCloneException(
      "Object instance does not support deepCloneing.");
  }

  @SuppressWarnings("unchecked")
  DeeplyClonableHashTable<T1,T2> copy = (DeeplyClonableHashTable<T1,T2>)o;
  Set<T1> keys = copy.keySet();

  for (T1 key: keys){
    T2 value = this.get(key);
    T1 keyCopy = key.deepClone();  // this line is in error
    T2 valueCopy = value.deepClone();  // this line is in error
    copy.put(keyCopy, valueCopy);
  }
  return copy;
  }
} 
于 2011-11-12T05:21:26.783 回答