This code
public class classObject{
classObject c = new classObject();
static String s = "It works!";
public static void main (String[] args){
classObject obj = new classObject();
System.out.println(s);
}
}
gives the following exception:
Exception in thread "main" java.lang.StackOverflowError
at classObject.<init>(classObject.java:2)
at classObject.<init>(classObject.java:2)
at classObject.<init>(classObject.java:2)
at classObject.<init>(classObject.java:2)
[...]
But I wonder why this program gives stack overflow exception, when it should in fact be giving a heap overflow exception. I think this because when main starts executing an object of class classObject
is created, but an object of the same class is also a variable of the class, hence another object is created as instance variable of the original object. This goes on and we end up having too many objects.
But these objects are allocated on heap. Hence we should have heap overflow. But this seems not to be the case. Why?