Search code examples
javainheritanceinterface

Why is this Java function signature marked as wrong for overriding?


Following situation

This Interface

public Interface ObjectService<T> {

  public T fromMNO(MNO<T> mno);

}

gets used by this abstract class

public AbstractObjectService<T> implements ObjectService<T> {

  public abstract T fromMNO (MNO<T> mno);

}

implemented in this class

public DummyService extends AbstractObjectService<DummyObj> {

  @Override
  public DummyObj fromMNO (DummyMNO mno) {
    //do stuff
    return new DummyObj();
  }

}

using this interface and interfaced object

public interface MNO<T> {}


public class DummyMNO implements MNO<DummyObj> {}

and a normal object

public class DummyObj {}

Now the problem is: DummyService#fromMNO gets flagged as not overrideable in VS Code bc of a type mismatch.

But as far as I understand DummyService with T as DummyObj results in public DummyObj fromMNO (MNO<DummyObj> mno) and DummyMNO IS A MNO<DummyObj>?

Am I wrong or is there something else fishy?

A "solution" would be to keep the "original type" and cast like this

@Override
  public DummyObj fromMNO<T> (MNO<DummyObj> mno) {
    DummyMNO d = (DummyMNO) mno;
    //do stuff
    return new DummyObj();
  }

which solves the problem of the error, but undermines the explicit type I wanted to achive.


Solution

  • As @Seelenvirtuose pointed out, yes, it is impossible to change the signature of the function.

    However it is possible to change the required type by using

    public Interface ObjectService<T, M extends MNO<T>> {
    
      public T fromMNO(M mno);
    
    }
    
    public AbstractObjectService<T, M extends MNO<T>> implements ObjectService<T, M> {
    
      public abstract T fromMNO (M mno);
    
    }
    
    public DummyService extends AbstractObjectService<DummyObj, DummyMNO> {
    
      @Override
      public DummyObj fromMNO (DummyMNO mno) {
        //do stuff
        return new DummyObj();
      }
    
    }