5

I want to implements a generic interface in a class. Consider implementing this generic interface:

public interface Lookup<T>{
  public T find(String name);
}

and this is the not generic class that implement Lookup:

public class IntegerLookup implements Lookup<Integer>{
  private Integer[] values;
  private String[] names;

  public IntegerLookup(String[] names, Integer[] values) {......}
  //now I want to write the implemented method - find

and my question is: how do I need to write this implemented method? I need to override it? yes?

public Object find(String name){...}

will be good? or:

public Integer find(String name){...}
5
  • 3
    Anywhere T is used in the super type, Integer should be used in the subclass that uses Integer as a type argument for T. Commented Jul 10, 2014 at 17:17
  • And why can't you just try it with an @Override annotation? Commented Jul 10, 2014 at 17:18
  • @SotiriosDelimanolis but it was written Object not T in the super type... or I am getting wrong? Commented Jul 10, 2014 at 17:18
  • The super type, Lookup, has declared the method's return type as T. Commented Jul 10, 2014 at 17:19
  • Do you want a utility method that looks up strings but returns a flexible type based on how it's called? Commented Jul 14, 2014 at 7:31

2 Answers 2

3

The syntax here

public class IntegerLookup implements Lookup<Integer>{
//                                           ^

binds the type argument provided, ie. Integer, to the type variable declared by Lookup, ie. T.

So,

public Integer find(String name){...}

This is the same as doing

Lookup<Integer> lookup = ...;
lookup.find("something"); // has a return type of Integer
Sign up to request clarification or add additional context in comments.

Comments

0

From your comments it sounds like you really want to use Object as the return type. I can't imagine why you would want to do that, but if so, you actually need to implement Lookup< Object >, not Lookup< Integer >.

But don't do that. Use Integer as the return type, since that type is standing in for T in your implementation.

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.