Java : Class inheriting self

后端 未结 8 1811
悲&欢浪女
悲&欢浪女 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:35

    The java compiler is not going to enter into an infinite loop when trying to enter a cyclic inheritance chain. After all, every inheritance chain is a eventually finite graph (and, computationally speaking, with a very small number of nodes and edges.) More precisely, the inheritance graph from subclass A to (eventual) superclass Z must be a line (not the other way around, though), and the compiler can easily determine if it is a line or not.

    It does not take much for a program to determine if such a small graph is cyclic or not, or if it is a line or not, which is what the compiler does. So the compiler does not go into an infinite loop, and the JVM never runs out of stack space since 1) neither the compiler runs on the JVM, nor 2) the JVM get to executes (since nothing gets to compile and the compiler never invokes under such conditions the JVM anyways.)

    I'm not aware of any languages that permit such cyclic inheritance graphs (but I've been doing nothing but Java for 11 years, so my memory of anything other than Java is mushy.) I cannot see, furthermore, the use of such a construct (in modeling or real life). Might be theoretically interesting, though.

    edit

    Ok, I ran your code and indeed it causes an stack overflow. You were right. I'm gonna have to sit and really study this to understand why the compiler allows such a construct.

    Nice find!!!!

提交回复
热议问题