Use Java generics in interfaces to enforce methods with implementation types as parameters

I have such an interface:

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

There is also 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 to enforce the "public void copyfrom (dataobjectimpl source)" method in the DataObject interface using generics or other methods?

Solution

If you only need to process copyfrom, and if the DataObject it gives is of the same type as the object itself, you only need to perform the following operations:

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

On the other hand, you can do this by using different names for methods that adopt implementation types But I don't know what use it is

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) { ... }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>