Search code examples
javaobjectstack-overflow

calling a method through an instance is throwing a stackOverFlow Error


I am working on the following scenario where I create an instance of a class and call a method on that instance.It ends up giving me a stackOverFlow Error. My code:

public class test {
    test t = new test();
    public  void show(){
    System.out.println("df");
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    test t = new test();
    t.show();
}

Solution

  • This throws a StackOverflowException because every test has the line

    test t = new test()
    

    which will create a new test, which will call that same line of code again, which will... you can see how this creates an infinite chain of calls.

    You should just remove that line. It would not be needed even if it did what you wanted it to since you already create a new test inside your main method.