Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an instance of generic subclass? Getting error: "Bound mismatch: The type ... is not a valid substitute for the bounded parameter ..."

public class ChampionsLeague<Team extends Comparable<Team>> extends League<Team>{
...

How do I make an instance of this class?

ChampionsLeague<Team> league = new ChampionsLeague<>();

This does not work:

"Bound mismatch: The type Team is not a valid substitute for the bounded parameter <Team extends Comparable<Team>> of the type ChampionsLeague<Team>"

like image 352
Peter Bauer Avatar asked Dec 04 '25 07:12

Peter Bauer


1 Answers

In your code, Team is just a placeholder (in this context, called Type Variable) and happens to be hiding the type Team, not referencing it. In other words, that declaration is equivalent to:

public class ChampionsLeague<T extends Comparable<T>> extends League<T> {

So it is really only asking for a class (or interface) that implements (extends) Comparable of itself. So this example:

public class Ball implements Comparable<Ball> {
    @Override
    public int compareTo(Ball o) { return 0; }
}
// or: public interface Ball extends Comparable<Ball> { }

Will work:

ChampionsLeague<Ball> test = new ChampionsLeague<Ball>();


Edit:

Some possibilities to what you may be trying to achieve:

// ChampionsLeague needs a type Comparable to Team
public class ChampionsLeague<T extends Comparable<Team>> extends League<T> {

or

// ChampionsLeague needs a subtype of Team
// In this case, you can make Team implement Comparable<Team> in its own decl.
public class ChampionsLeague<T extends Team> extends League<T> {
like image 103
acdcjunior Avatar answered Dec 06 '25 21:12

acdcjunior