3

I have an interface which just contains one generic method:

public interface Presenter {
    <T> void query(T queryParameter);
}

Now, I want to define a subclass of Presenter and I want the type to be String, just like this:

public class IpQueryPresenter implements Presenter {
    void query(String queryParameter) {
         //do something here...
    }
}

How to define it ?

I saw all your answers define the type on the interface name, but is it a must ? Is it possible if I just want to define a generic method and override it ?

L. Swifter
  • 3,179
  • 28
  • 52

3 Answers3

5

First of all, from your code I'm assuming you are implementing an interface, not extending a class (though your IpQueryPresenter class has neither extends or implements clause).

You can move the generic type parameter to the interface level :

public interface Presenter<T> {
    void query(T queryParameter);
}

And then :

public class IpQueryPresenter implements Presenter<String> {
    void query(String queryParameter) {
         //do something here...
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
3

Make the interface itself generic and define your type in your sub class

public interface Presenter<T> {
    void query(T queryParameter);
}

public class IpQueryPresenter implements Presenter<String>  {
    void query(String queryParameter) {
         //do something here...
    }
}
shalama
  • 1,133
  • 1
  • 11
  • 25
2

Define T on the interface, i.e. like this:

public interface Presenter<T> {
 void query(T queryParameter);
}

Then set the type in the implementation:

public class IpQueryPresenter implements Presenter<String> {
  //note that you need to make the method public
  public void query(String queryParameter) {
     //do something here...
  }
}
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • Thanks for your comment and answer, but I still wonder that is it possible to do this without defining `T` on the interface ? – L. Swifter Aug 16 '16 at 09:07
  • @L.Swifter that wouldn't really make sense since defining `T` on the method would mean you want to infer the type from the assignment or the parameters. Additionally think of operating on a variable like `Presenter p`. How should the compiler know that a certain implementation of that interface only allows strings (and why should it bother in your opinion)? – Thomas Aug 16 '16 at 09:41