Reputation: 4267
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?
Upvotes: 2
Views: 3084
Reputation: 140319
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.
Upvotes: 8
Reputation: 5482
You can try like this :
public interface i<M extends Image>{
void setImage(M image);
}
Upvotes: 0