Java : Class inheriting self

后端 未结 8 1340
刺人心
刺人心 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:40

    In its final form this problem has nothing to do with cyclic inheritance and inner classes. It's just an infinite recursion caused by unbound recursive constructor call. The same effect can be shown by the following simple example:

    public class A {
        public A() {
            new A();
        }
    }
    

    Note that this code is perfectly valid, since Java doesn't apply any restrictions on recursive calls.

    In your case it's slightly more complicated due to inheritance, but if you recall that constructor of subclass implicitly call a constructor of superclass, it should be clear that these calls form infinite recursion.

提交回复
热议问题