Java : Class inheriting self

2019-03-27 07:23发布

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();
    }
}

8条回答
祖国的老花朵
2楼-- · 2019-03-27 08:15

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

查看更多
祖国的老花朵
3楼-- · 2019-03-27 08:17

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.

Inside o = new Inside(0);

Since Inside extends Outside, Inside first calls the super() method implicitly (since you've not called it yourself). Outside() constructor initializes Inside o and the cycle runs again, until the stack is full and it overflow (there's too many Inside and Outside inside the heap stack).

Hope this helps especially Vladimir Ivanov.

查看更多
登录 后发表回答