Avoid Stack Overflow from Overridden Methods in Java (and How to Fix It)
In the vast landscape of object-oriented programming, method overriding is a cornerstone for achieving polymorphism and dynamic method dispatch. It’s elegant and powerful—but like all tools, it carries inherent risks. One particularly insidious i...

class Parent {
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
@Override
void display() {
display(); // Calls itself recursively
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}
- In this code, the Child class overrides the display method.
- Within display, it inadvertently calls itself instead of the parent’s method, leading to infinite recursion.
class Parent {
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // Explicitly calls the parent method
System.out.println("Child display");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}
- The super.display() ensures that the parent’s implementation is executed, breaking the cycle.
- The stack is now safely managed, and the method outputs both "Parent display" and "Child display."
class FactorialCalculator {
int calculateFactorial(int n) {
if (n <= 1) {
return 1; // Base condition
}
return n * calculateFactorial(n - 1);
}
}
public class Main {
public static void main(String[] args) {
FactorialCalculator calc = new FactorialCalculator();
System.out.println("Factorial: " + calc.calculateFactorial(5)); // Outputs 120
}
}
- The base condition (if (n <= 1)) ensures the recursion terminates.
- Without this, the method would run indefinitely and cause a StackOverflowError.
- Long stack traces that obscure the root cause.
- Cyclic method calls spanning multiple classes or packages.
java -Xss2m Main
- This is a temporary solution and doesn’t address the root cause.
class FactorialCalculator {
int calculateFactorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
public class Main {
public static void main(String[] args) {
FactorialCalculator calc = new FactorialCalculator();
System.out.println("Factorial: " + calc.calculateFactorial(5)); // Outputs 120
}
}
Read more at : Avoid Stack Overflow from Overridden Methods in Java (and How to Fix It)
About the author
I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
Comments
Join the discussionNo comments yet. Be the first to comment.





