The following editor will bring you an article about the infinite loop of Java non-static member variables (detailed explanation). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.
1. Non-static member variables
When the member variable is a non-static member variable and is specific to the current class When instantiating, an infinite loop will occur
Example:
public class ConstructorCls { private ConstructorCls obj=new ConstructorCls(); }
public class TestC { public static void main(String[] args) { ConstructorCls c =new ConstructorCls(); } }
Result:
Exception in thread "main" java.lang.StackOverflowError at com.ConstructorCls.<init>(ConstructorCls.java:7) at com.ConstructorCls.<init>(ConstructorCls.java:7) at com.ConstructorCls.<init>(ConstructorCls.java:7)
Analysis: When new ConstrutorCls() will instantiate ConstrutorCls, Then the member obj of this class is initialized, and obj instantiates its own class. This continues until StackOverflowError
2. Static member variables
Static member variables belong to the class and there will be no infinite loop
For example:
public class ConstructorCls { private static ConstructorCls obj=new ConstructorCls(); }
public class TestC { public static void main(String[] args) { ConstructorCls c =new ConstructorCls(); } }
Analysis: When new ConstructorCls(), ConstructorCls is first added to the JVM, and the static content of the class is loaded when loading. Initialize the members (only once when loading), initialize the obj object, and create a new ConstructorCls. A key point here is that this static member belongs to the class and does not belong to an instance object, so an infinite loop will not occur.
The above is the detailed content of Detailed explanation of the infinite loop of non-static member variables in Java. For more information, please follow other related articles on the PHP Chinese website!