简体   繁体   中英

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

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.

You have a bad recursive call on instantiating test instances inside class test . It keeps instantiating new instances until no heap space left. When you have StackOverflowError the first thing you need to check is whether anywhere in your code called itself repeatly or not.

Why you create that new instance of class inside the class ? Delete Test t = new test(); inside Test class and try again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM