2

I am writing a program where an overridded method must call a method in the parent class, which in turn must call the original method of the overridden method. The overridden method must then also call its parent method.

This is the code I have:

public class Cow 
{
  public float hiCat()
  {
    ...
    return meow;
  }

  public float dog()
  {
    float meowz = hiCat();
    ...
  }
}

public class Moo extends Cow
{
  public float hiCat()
  {
    float dogBark = dog();
    float meows = super.hiCat();
    ...
  }
}

Which gives me a stack overflow error like so:

Exception in thread "main" java.lang.StackOverflowError
at Moo.hiCat(Moo.java:12)
at Cow.dog(Cow.java:63)

Line 12 in Moo is float dogBark = dog(); and line 63 in Cow is float meowz = hiCat();.

I believe line 63 is the problem in dog().

It seems like hiCat() in class Moo is calling dog() in class Cow like it's supposed to, but then dog() is calling the overridded version of hiCat() instead of the one it shares a class with. This confuses me because I am calling hiCat() in a regular way with no modifiers or anything.

Why is this happening, and how can I fix it?

Note: the program's structure must remain the same.

Main method is completely unrelated to the methods at hand:

public static void main(String[] args) 
{
    InputClass input = new InputClass();
    input.GenerateGUI();
}
Biglulu
  • 21
  • 7

3 Answers3

0

It is because you are calling dog() in side the overriding method of hiCat(), then when you the method executed, this line float dogBark = dog() calling dog() method then inside of dog() method in the super class calling again the hiCat(); and hiCat(); again calling dog() because the hiCat(); method is overriding by sub class then it will call the the overriden one of hiCat(); method..... so StackOverflowError happens

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
0

You created cyclic dependency among your methods. Best way to handle these type of situations is to refactor the code and create private method _hiCat()

public class Cow 
{

private float _hiCat()
{
   ...
   return meow;
}

public float hiCat()
{
   return _hiCat();
}

public float dog()
{
   float meowz = _hiCat();
   ...
}
}

public class Moo extends Cow
{
 public float hiCat()
{
float dogBark = dog();
float meows = super.hiCat();
...
}
}
Pankaj Arora
  • 544
  • 2
  • 6
0

A similar question exists over here, which has the correct explanation: Java: Calling a super method which calls an overridden method

I solved my particular problem by changing the meowz variable in dog() to a class variable, and then hiCat() can save to that variable, thus negating the need to call hiCat() from dog() and avoiding the infinite recursion.

Note that I also tested this in C#, and it does work with this setup. It appears that only Java has this problem.

Community
  • 1
  • 1
Biglulu
  • 21
  • 7