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();
}
}
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 Interview
s first. You should almost certainly remove the i1
field from the Interview
class.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With