Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Class inheriting self

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();
    }
}
like image 746
TurtleToes Avatar asked Mar 24 '11 10:03

TurtleToes


3 Answers

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
                 //   ...
    }
}
like image 119
aioobe Avatar answered Nov 19 '22 04:11

aioobe


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.

like image 22
axtavt Avatar answered Nov 19 '22 02:11

axtavt


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

like image 1
GuruKulki Avatar answered Nov 19 '22 03:11

GuruKulki