-3

i create a class as below:

public class NodeOne {

    NodeOne nodeone = new NodeOne();

    public NodeOne() {
        System.out.println("1");
    }

    public static void main(String[] args) {
        NodeOne nodeone = new NodeOne();
    }
}

once i run it i got exception "Exception in thread "main" java.lang.StackOverflowError ",which i know the reason for sure. but when i add the modifier "static" before the field nodeone, the result turn out to be fine. so what's the deep cause?

public class NodeOne {

    static NodeOne nodeone = new NodeOne();

    public NodeOne() {
        System.out.println("1");
    }

    public static void main(String[] args) {
        NodeOne nodeone = new NodeOne();
    }
}

output:
1

1

gibbyhou
  • 7
  • 2

3 Answers3

2

In first case, each time you create new object NodeOne its default constructor is calling another contructor for its field nodeone. And it happens again, and again, and again... Till the stack is full.

When it's static, it is called only one time, with first usage of this class.

rzysia
  • 737
  • 1
  • 11
  • 26
1

The problem with the first example is that the the NodeOne class contains an instance of the same class.

When the class is initialized the member field is initialized, wich in turn causes its own field to be initialized and so on, in a never ending loop (actually it ends when the jvm reaches the maximum stack size, as every constructor called uses a bit of it).

It's generally considered to be bad practice to have such a field in a class, as it can lead to this type or errors. Note that it is ok to instantiate the class in main.

Iamsomeone
  • 233
  • 2
  • 15
0

Your problem here is that you're making a recursive call. When you call the constructor NodeOne(), it tries to go to the class NodeOne and check for its attributes. It finds the attribute nodeone there, which needs an instantiation using the constructor, which will allocate a new memory address for the new instance. This instance also contains the attribute nodeone, which also needs instantiation. Here it loops and loops until it consumes all the JVM memory. But if you use static it will allocate only a single memory address, whose content java will modify for every instantiation.

BobRodes
  • 5,990
  • 2
  • 24
  • 26