0

I am trying to enforce a particular subclass type on an abstract method, like so:

public abstract class Searcher {    
  public abstract SearchResult search(<T extends SearchInput> searchInput);
}

This is to ensure that subclasses of Searcher have to extend a corresponding subclass of SearchInput. I know I can use a bounded type for the method's return type, but I can't seem to get it to work as a method argument. Is this possible in Java?

IVR Avenger
  • 15,090
  • 13
  • 46
  • 57
  • 1
    You need to declare the method's generic parameter first: `public abstract SearchResult search(T input)` - you declare it before the return type, not in the parameters. However, declare on how the type will be used, you may want to add the type parameter on the class itself, instead of the method. – Vince Feb 10 '21 at 00:56
  • 1
    That should be a generic parameter of the class, i.e. `public abstract class Searcher {` and then you can accept `T` in `search`. In subclasses, you do `class Subclass extends Searcher`. – Sweeper Feb 10 '21 at 00:57

1 Answers1

1

Have a look at Java documentation on Generic Methods:

The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.

You need:

public abstract class Searcher {
    public abstract <T extends SearchInput> SearchResult search(T searchInput);
}

Point is, that generic type declaration must happen before the signature part.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66