简体   繁体   中英

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> "

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> {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM