views:

79

answers:

2

I have an interface like this:

public interface DataObject {
    ...
    public void copyFrom(DataObject source);
    ...
}

And a class that implements it:

public class DataObjectImpl implements DataObject {
    ...
    @Override
    public void copyFrom(final DataObject source) {...}

    public void copyFrom(final DataObjectImpl source) {...}
    ...
}

Is there any way that I can enforce the implementation of a "public void copyFrom(DataObjectImpl source)" method in the DataObject interface, using generics or otherwise?

+2  A: 

If you just need to handle copyFrom differently if the DataObject it's given is the same type as the object itself, just do something like this:

public class DataObjectImpl implements DataObject {
  public void copyFrom(final DataObject source) {
    if (source instanceof DataObjectImpl) {
      ...
    }
    else {
      ...
    }
  }
}

On the other hand, you could do it like this, using a different name for the method taking an implementation type. However, I don't see what good this does.

public interface DataObject<T extends DataObject<T>> {
  public void copyFrom(DataObject source);
  public void copyFromImpl(T source);
}

public class DataObjectImpl implements DataObject<DataObjectImpl> {
  public void copyFrom(final DataObject source) { ... }
  public void copyFromImpl(final DataObjectImpl source) { ... }
}
ColinD
"public void copyFrom(T source);" has the same type erasure as "public void copyFrom(DataObject source);". I need the interface to specify both.
Ioeth
@loeth: Why do you need that? If you need to handle things differently when the `copyFrom` parameter is a `DataObjectImpl` vs. when it's some other implementation of `DataObject`, just use the `copyFrom(DataObject source)` signature and do an `instanceof` check in the implementation.
ColinD
@ColinD: I need to do this because currently, all classes implementing the interface do of course specify "public void copyFrom(DataObject source)", but our goal is to move towards the "public void copyFrom(DataObjectImpl source)" methods. However, in the meantime we have hundreds of objects that we don't wish to remove the DataObject method from until the DataObjectImpl method has been specified in the interface for at least one version.
Ioeth