I know this is pointless: I just find it funny and I want to inquire more about the mechanics of what happens when you create a class that inherits itself, resulting in a stack overflow crash. It's amazing that Java allows you to make such a construct to begin with.
I am just guessing, but is the JVM putting itself into an infinite loop trying to resolve the class before instancing it, or is it actually instancing multiple copies of the class endlessly?
I should have been more specific; I am using an inner class to derive from enclosing class.
public class Outside {
private int outsideValue;
public class Inside extends Outside {
private int insideValue;
public Inside(int val) {
insideValue = val;
}
}
public Outside() {
Inside o = new Inside(0);
}
}
public class Main {
public static void main(String args[]) {
Outside o = new Outside();
}
}
Try in an IDE like eclipse, it wont allow you to do so. ie gives an error like this.
Cycle detected: the type Test cannot extend/implement itself or one of its own member types
Extending oneself generates an error of cyclic inheritance (which java doesn't allow). Your code sample does compile and is valid.
Due to Vladimir Ivanov's persistence, I will fix my edit.
Your code throws a
StackOverflowError
because of the following.Since
Inside
extendsOutside
,Inside
first calls thesuper()
method implicitly (since you've not called it yourself).Outside()
constructor initializesInside o
and the cycle runs again, until the stack is full and it overflow (there's too manyInside
andOutside
inside the heap stack).Hope this helps especially Vladimir Ivanov.