Why I came across this and what is a workflow

Can anyone help in understanding StackOverFlowError while executing the code below. I can not understand the workflow. One of the interview Question :)

public class Interview { Interview i1 = new Interview(); Interview(){ System.out.println("Hello"); } public static void main(String[] args){ Interview i = new Interview(); } } 
+4
source share
5 answers

Your constructor is initializing. Here's what your constructor for the JVM looks like:

 Interview i1; Interview(){ super(); i1 = new Interview(); // this line calls the constructor System.out.println("Hello"); } 
+3
source

In your Interview i1 = new Interview(); It says that each Interview has its own Interview object, which belongs to it, and therefore, as soon as you call new Interview() in main , the system starts trying to create a new Interview for this and a new Interview for this ...

It does not even make it constructor (explicit), because the system first shuts down in the endless chain of the new Interview . You will almost certainly remove the i1 field from the Interview class.

+3
source

You create a new Interview every time you create an instance of Interview . This results in an endless loop of calls and constructor instances that ultimately run out of stack space (because the function call takes up stack space).

Note that if you had infinite stack space available to you, you will ultimately fail out of all the Interview objects allocated on the heap.

+2
source

Since after initialization this first Interview() in the main() it creates and initializes second Interview , which creates and initializes another, etc.

+1
source

All initialization that you perform in the fields will become part of the constructor without parameters. In this case

So your code will become

 public class Interview { Interview i1; Interview() { super();//by default calls the constructor of Object i1 = new Interview();//initialization becomes part of constructor System.out.println("Hello"); } } 

This will now recursively set up an interview that raises an exception.

0
source

Source: https://habr.com/ru/post/1502227/


All Articles