Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am i facing this and what is workflow

Tags:

java

Could anyone please help in understanding the StackOverFlowError at runtime in below code. I am not able to understand 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();

    }

}
like image 611
Rajan Wadhwa Avatar asked Jan 12 '23 09:01

Rajan Wadhwa


2 Answers

Your Interview i1 = new Interview(); says that each Interview has its own Interview object that belongs to it, and so once you call new Interview() in main, the system starts trying to create a new Interview for that one, and a new Interview for that one...

It never even makes it to the (explicit) constructor, because the system goes off on a never-ending chain of new Interviews first. You should almost certainly remove the i1 field from the Interview class.

like image 137
chrylis -cautiouslyoptimistic- Avatar answered Jan 18 '23 23:01

chrylis -cautiouslyoptimistic-


Your constructor is initializing itself. This is what your constructor looks like to the JVM:

Interview i1;
Interview(){
    super();
    i1 = new Interview(); // this line calls the constructor
    System.out.println("Hello");
}
like image 26
Alex Gittemeier Avatar answered Jan 19 '23 00:01

Alex Gittemeier