I have a Interface Foo which has a generic type -
public interface Foo<T> {
boolean apply(T t);
}
Having another class Bar which implements this interface but what I want is the generic Type of Bar should be a Collection of type Interface A and B, With the below definition its giving compiler error -
public class Bar implements Foo<Collection<? extends A & B>>{
@Override
public boolean apply(Collection<? extends A & B> collect){
...
}
}
Can you suggest the correct way to achieve this?
I can use multiple bounds at method level only?
Multiple parametersYou can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
A type parameter can have multiple bounds.
Java generics upper bounded wildcard : Upper bounded wildcard is used to restrict the unknown type to be a specific type or a subtype of that type using '? ' with extends keyword.
Wouldn't this work?
public class Bar<T extends A & B> implements Foo<Collection<T>>{
@Override
public boolean apply(Collection<T> collect){
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With