2

Let's say I have this interface:

public interface i{ 
     void setImage(Image image);
}

I want that class methods that implements that interface method are allowed to accept as method paramether not only Image, but all classes that extends Image.

What I need inside the interface is something like:

<T extends Image> void setImage(T image);

But of course, this is not the right way to do it How should I write a generic method in an Interface?

MDP
  • 4,177
  • 21
  • 63
  • 119
  • 1
    What do you plan to do that is class-specific? I ask this because taking `Image` as a parameter already does allow for all subclasses of Image. – Zircon May 20 '16 at 14:57
  • 3
    The non-generic form already accepts things that extend `Image`. – Andy Turner May 20 '16 at 14:58
  • 1
    Relevant http://stackoverflow.com/questions/29618425/how-implement-an-interface-generic-method also (potential dupe) http://stackoverflow.com/questions/20989740/it-does-not-make-sense-to-have-generic-method-in-interface – Tunaki May 20 '16 at 15:02

2 Answers2

8

You are allowed to declare the method with the generic in the interface:

<T extends Image> void setImage(T image);

but this actually isn't very much use: the only methods you can invoke on image are those defined on Image, so you might as well just declare it non-generically:

void setImage(Image image);

and this will accept parameters of type Image or any subclass.


Declaring a method-level type variable might be useful if, say, you wanted to return a variable of the same type as the parameter:

<T extends Image> T setImage(T image);

or if you need to constrain generic parameters to types related to other parameters:

<T extends Image> void setImage(T image, List<T> imageList);

It wouldn't help you without generic parameters, e.g.

<T extends Image> void setImage(T image1, T image2)

since you could pass in any two subclasses of Image; again, you may as well do it non-generically.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can try like this :

public interface i<M extends Image>{ 
     void setImage(M image);
}
Rambler
  • 4,994
  • 2
  • 20
  • 27