Why am I getting this compiler error on FuzzyWuzzyContainer?
Bound mismatch:The type FuzzyWuzzy is not a valid substitute for the bounded parameter
<T extends Fuzzy & Comparable<T>>
of the type FuzzyContainer
FuzzyWuzzy does in fact implement both interfaces that are defined in the bounded generic.
public interface Fuzzy
{
boolean isFuzzy();
}
public class FuzzyWuzzy implements Fuzzy, Comparable<Fuzzy>
{
public boolean isFuzzy() {return true;}
public int compare(Fuzzy o) {return 0;)
}
public abstract class FuzzyContainer<T extends Fuzzy & Comparable<T>>
{
:
}
public class FuzzyWuzzyContainer extends Fuzzycontainer<FuzzyWuzzy> // Error is here
{
}
Multiple BoundsBounded type parameters can be used with methods as well as classes and interfaces. Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can't have more than one class in multiple bounds.
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
By default, the upper bound is type Object unless specified otherwise in the type parameter section.
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.
The problem is FuzzyWuzzy implements Comparable<Fuzzy>
. The FuzzyContainer
is expecting both T
s in FuzzyContainer<T extends Fuzzy & Comparable<T>>
to be the same type. FuzzyWuzzy
implements Fuzzy
but it doesn't implement Comparable<FuzzyWuzzy>
.
Try, FuzzyWuzzy implements Fuzzy, Comparable<FuzzyWuzzy>
Try declaring FuzzyContainer
like this:
public abstract class FuzzyContainer<T extends Fuzzy & Comparable<? super T>>
This is necessary since FuzzyWuzzy
implements Comparable<Fuzzy>
rather than Comparable<FuzzyWuzzy>
(you could also make that change, as The Cat pointed out).
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