简体   繁体   中英

Passing abstract class as type in parameter, unable override method. Do I have a misunderstanding of polymorphism in java?

public abstract AbstractGameStats<A extends GameStats> { 
    public abstract A addGameSpecificStats(final A gameStats, final LiveStats liveStats);
}

public abstract class LiveStats { // }

public class FootballStats extends LiveStats { // }

public class FootballLiveGameStats extends AbstractGameStats<FootballGameStats> { 
    @Override
    public FootballGameStats addGameSpecificStats(final FootballGameStats gameStats, final FootballStats footballStats) {}
}

Doing this tells me im not overriding the parent method because in addSpecificGameStats, im passing in the subclass of FootballStats rather than the LiveStats parent class. I dont understand what the problem is here. Why cant i just pass in the base type? Isnt this the whole point of polymorphism?

addGamespecificStats takes a LiveStats argument (second). Any method overriding this must also accept LiveStats . Your overriding method only accepts FootballStats but not BaseballStats (assuming this is also a subclass of LiveStats ). The point is: An overriding method may accept more but not less. Imagine:

AbstractGameStats<...> a = new FootballGameStats();
a.addGameSpecificStats(gameStats, baseballStats);

This would be legal because AbstractGameStats.addGameSpecifigStats accepts LiveStats and all subclasses. But your overriding method would not.

Overridden methods must have the same name, number and type of parameters, and return type as the method they override - that's the rule. (You can do however return a sub-type of the type that the overridden method returned, but you don't need this).

What you can do is just use your second argument as is, and downcast when necessary (Ideally you should aim to handle your objects by the interface and avoid the casting).

You can also add a further template argument to provide more specialized handling or type safety, like this:

public abstract class AbstractGameStats<A extends GameStats, B extends LiveStats> { 
    public abstract A addGameSpecificStats(final A gameStats, final B liveStats);
}

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