1

How can I implement, for example, a String type of a non-generic-interface with a generic method?

Here is the interface:

// non-generic-class
interface I{

    public <T> T doI(T t);

}
7
  • the same way the method is defined in the interface, just with method body. Commented Apr 14, 2015 at 3:00
  • mmm you are returning the same type provide as parameter. You could modify the object by reference and make doI void??? Commented Apr 14, 2015 at 3:04
  • good question, I don't know. Commented Apr 14, 2015 at 3:06
  • Java use two modes by reference and value. You can use it in in your Interface. HttpServlet.doGet is a good example it's void and the client modify the object by reference Commented Apr 14, 2015 at 3:09
  • 1
    why <T> and T for return type of method? I know that the compiler has no issue with that but trying to imagine the requirement for it. could you please explain briefly what needs to be achieved. good question by the way. Commented Apr 14, 2015 at 3:35

1 Answer 1

2

All the <T> in this interface means is that the type T passed to the method is the same as the type T returned from the method.

Implementation requires some use of the symbol T as if it was a class Like

public <T> T doI(T t){
    Object a = t.getClass().newInstance();
    return (T) a;
}

You can then call it with something like

I obj = getIImplementer ();
String a = obj.doI ("ssssssss");

And the compiler knows it can infer the return type from the object type passed.

If you want to implement a specific version you need to put the generic parameter on the interface rather than the method so you can type the implementing class and therefore the method parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.