Home > database >  How to implement function in interface with generic argument types?
How to implement function in interface with generic argument types?

Time:10-07

public interface Page<T> {
  T nextPage();
}

And it's implementation

public class ConcretePageA implements Page<TypeA> {
  public TypeA nextPage() {
    // do stuff
  }
}

Then I have an interface that consumes Page

public interface Source {
  <T> int getData(Page<T> page)
}

And its implementation

public class ConcreteSourceA implements Source {
  public int getData(Page<TypeA> page) {   //error: getData in ConcreteSourceA clashes with getData in Source
    // do stuff
  }
}

I tried this but it won't work either

public class ConcreteSourceA implements Source {
  public <TypeA> getData(Page<TypeA> page) { // error: expect com.foo.TypeA but got TypeA
    // do stuff
  }
}

When I do the above I get a compile error saying

getData in ConcreteSourceA clashes with getData in Source

I know I am doing something wrong, but how do i fix it while still having multiple implementations that uses different types?

Am I just doing this wrong in the first place? Is Generics not the right way to go about this?

CodePudding user response:

It looks like you want to make Source generic much like Page is - like so:

public interface Source<T> {
  int getData(Page<T> page);
}

You can then define implementations that only implement certain specializations of that like

public class ConcreteSourceA implements Source<TypeA> {
  public int getData(Page<TypeA> page) {
    // do stuff
    return 0;
  }
}
  • Related