Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing generic interface in not generic class

Tags:

java

generics

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){...}
like image 312
Yuval Levy Avatar asked Oct 21 '22 05:10

Yuval Levy


1 Answers

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
like image 184
Sotirios Delimanolis Avatar answered Oct 23 '22 09:10

Sotirios Delimanolis