Java : Class inheriting self

后端 未结 8 1318
刺人心
刺人心 2021-02-15 11:19

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

相关标签:
8条回答
  • 2021-02-15 11:50

    The example you posted could get problematic if we change it a bit more:

    public class Outside {
    
        public class Inside extends Outside {
    
                public Inside(int val) {
            }
    
        }
    
        private Inside i;
    
        public Outside() {
            i = new Inside();
        }
    }
    

    But this is not really related to the fact that Inside is an inner class of Outside, it could have happened with separate top-level-classes identically.

    0 讨论(0)
  • 2021-02-15 11:53

    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.

    0 讨论(0)
提交回复
热议问题