I am not sure why this code (gives stackoverflow at runtime) compiles:
import java.io.*;
import java.util.*;
public class StackOverflow {
StackOverflow overflow = new StackOverflow();
public void myCall() {
overflow.myPrint();
}
public static void main(String[] args) {
StackOverflow newStackOverflow = new StackOverflow();
newStackOverflow.myCall();
}
public void myPrint() {
System.out.println("I am confused!");
}
}
The reason why I am confused is coz, within the class definition, I am trying to create an object of the class I am trying to define. Shouldn’t this be a compile time error?
It’s not a compile-time error because the compiler can’t tell if it’s going to be infinitely generated at compile-time.
You and I can look at that and see it for sure, but the compiler only cares that the declarations are correct. There’s nothing syntactically illegal about this declaration, which is why the compiler will just let it go.
It’s related to the halting problem, in that a program can’t report if it will successfully halt.