-3

My question is related to another question: How does creating a instance of class inside of the class itself works?

I created two classes as follows:

class Test {
  Test buggy = new Test();
  public static void main (String[] args) {
    Test test = new Test();
    System.out.println("Done");
  }
}

And another:

class Test {
  static Test buggy = new Test();
  public static void main (String[] args) {
    Test test = new Test();
    System.out.println("Done");
  }
}

I do not understand why the first code (without static variable) gave the stack-overflow error but when I declare the instance variable to be static (the second case) I got no error. What difference does the static keyword makes here?

Community
  • 1
  • 1
sarthak
  • 774
  • 1
  • 11
  • 27
  • 1
    In the first code, you create one instance of Test with another instance being created inside. That creates an infinite loop. – f1sh Dec 22 '16 at 13:43
  • 2
    Go through what happens for the first when you initialize a `Test`. What happens when you Initialize a single `Test`? It has a variable `buggy`, which gets initialized, it´s of the type `Test`. This `Test` also has a variable `buggy` of the type `Test` which wants to get initialized aswell. Guess what? you now have another variable `buggy` which wants to get initialized. This happens until you overflowed your `Stack` with instances of `Test`. – SomeJavaGuy Dec 22 '16 at 13:43
  • http://softwareengineering.stackexchange.com/questions/211137/why-can-static-methods-only-use-static-data – koutuk Dec 22 '16 at 13:44

2 Answers2

8

The first snippet creates a new instance of your Test class whenever a new instance of your class is created. Hence the infinite recursion and stack overflow.

Test test = new Test(); // creates an instance of Test which triggers
                        // initialization of all the instance variables,
                        // so Test buggy = new Test(); creates a second
                        // instance of your class, and initializes its
                        // instance variables, and so on...

The second snippet, since here the variable is static, creates an instance of your class when the class is initialized. When new instances of your class are created, there is no infinite recursion.

Test test = new Test(); // this time buggy is not an instance variable, so it
                        // has already been initialized once, and wouldn't be
                        // initialized again
Eran
  • 387,369
  • 54
  • 702
  • 768
2

The static field is initialized only once, when the Test class is first loaded by the class loader.

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60