Java : Class inheriting self

后端 未结 8 1834
悲&欢浪女
悲&欢浪女 2021-02-15 11:21

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:37

    Remember that, since Inside extends Outside, it has an implicit call to super() which is the constructor of Outside (which in turn calls the constructor of Inside) and so it goes around.

    The code you posted is conceptually not different from the following program:

    class A {
        B b = new B();
    }
    
    class B extends A {
    }
    
    public class Test {
        public static void main(String[] args) {
            new A(); // Create an A...
                     //   ... which creates a B
                     //   ... which extends A thus implicitly creates an A
                     //   ... which creates a B
                     //   ...
        }
    }
    

提交回复
热议问题