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

Time:12-24

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.

CodePudding user response:

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();
  }

}

CodePudding user response:

The fromMNO method that you are overriding in the DummyService class has a type mismatch with the fnoMNO in AbstractObjectService.

One of the solution is you already put in the question that is changing the argument in the DummyService class's method, you can do it like this...

public DummyService extends AbstractObjectService<DummyObj> {
  @Override
  public DummyObj fromMNO (MNO<DummyObj> mno) {
    return new DummyObj();
  }
}

Else, You can change the original type in the AbstractObjectService

public abstract class AbstractObjectService<T> implements ObjectService<T> {

  public abstract T fromMNO (DummyMNO mno);

}
  • Related