0
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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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);
}

3 Comments

Overridden methods need not have the exact same argument types. But they may only accept more, not less. I.e. you can override a method that accepts Integer with one accepting Number or Object
No, you can not. At least until Java 11. Do you have an example of this? What version of the JLS?
Indeed you are right. Overriding methods must use the exact same signature. Anything else generates an additional method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.