Search code examples
javainheritancemethodspolymorphism

Java polymorphism not behaving the way I assumed it would


I'm having a bit of trouble understanding why my parent class isn't using the method of same signature available in the child class.

The code is a bit long, so I'll just show snippets of my code that I'm not understanding.

Parent class:

public GameOutcome endGame(GameState game) {
GameOutcome outcome = calculateOutcome(game);    
numberOfGames += 1;
switch(outcome) {

and the method that endGame is calling:

private GameOutcome calculateOutcome(GameState game) {
System.out.println("Wrong method being used");
switch(game) {
case XWIN:
  return myMove == CellValue.X ? GameOutcome.WIN : GameOutcome.LOSE;

Child:

private GameOutcome calculateOutcome(GameState game) {
int tracker;

switch(game) {
case XWIN:

My understanding is that the parent class will check if calculateOutcome exists in the child, before using the one in parent.

This code compiles and runs, but it isn't using the method that I want. (The one in the child)

The only thing I see that could be causing this problem is that the parent class is already using one of its functions to call another function, so it won't bother checking child?


Solution

  • Apologize for not posting this earlier.

    Basically I had to modify ONLY the child, without touching the parent.

    The issues that I had:

    1)The child was trying to override a private method, so it was always ignored.

    2)The Public parent method that could fix this had to modify several private methods, which I wasn't sure how to touch from the child.

    I solved it by overriding the Public Parent method, and then using super() so that the Parent modifies its own variables. This allowed me to keep the Private method I had to override as Private.

    I also apologize for my initial question not being clear enough.