Reputation: 2516
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){...}
Upvotes: 5
Views: 1344
Reputation: 280172
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
Upvotes: 3
Reputation: 5239
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.
Upvotes: 0