-1

I am getting StackOverflowError overflow exception when calling a method that only contains print statement.

Below is the code

public class Dog {

    Dog dog = new Dog();

    public static void main(String args[]){
        new Dog().bark();
    }

    public void bark(){
        System.out.println("Bark");
    }

}

But when i remove the Class variable(dog), code is working fine.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

3

Your problem is here:

public class Dog {

    Dog dog = new Dog();  //  ************** HERE ************

    public static void main(String args[]){
        new Dog().bark();
    }

    public void bark(){
        System.out.println("Bark");
    }

}

Your Dog class is creating a new version of itself whenever it is created with the call to new Dog(), which creates version of itself, which creates version of itself, which creates version of itself, which creates version of itself, which creates version of itself, which creates version of itself, which creates version of itself, which creates version of itself, etc...

Solution: Don't create a new Dog() within the Dog class, except within the main method! Note that there are other times where it is OK to create a new instance of the object within itself, but always be watchful of possible recursion when doing this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373