Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting compile error on type parameter with multiple bounds

Tags:

java

generics

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
{
}
like image 510
Robin Avatar asked Nov 15 '12 16:11

Robin


People also ask

Is it possible to declared a multiple bounded type parameter?

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.

What are bounded type parameters?

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.

Is the default upper bound of a type parameter?

By default, the upper bound is type Object unless specified otherwise in the type parameter section.

How do I restrict a generic type in Java?

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.


2 Answers

The problem is FuzzyWuzzy implements Comparable<Fuzzy>. The FuzzyContainer is expecting both Ts 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>

like image 163
The Cat Avatar answered Sep 18 '22 01:09

The Cat


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).

like image 36
Paul Bellora Avatar answered Sep 17 '22 01:09

Paul Bellora