Search code examples
javaconstructorsuper

Java Implicit super() call recursion


While I do not have an error, or any code on the matter due to my inexperience, the implicit call to super() in a child class's constructor has confused me.

If I am calling the constructor of a child, whose parent is also a child, etc. will there be a series of consecutive super() calls? As in, since the parent constructor also has an implicit call to super() will that call be made?

And if so, how deep can that go/how deep does it go?

I apologize if I have been confusing or asked an obvious question, my instructor didn't provide a satisfactory answer.


Solution

  • Constructor chain

    will there be a series of consecutive super() calls?

    Yes, that is exactly what happens. Each time you construct an object in Java, so new Foo(), it will first go up the full inheritance tree and start constructing the parents from top to bottom.

    So if you have a setup like

    class Chihuahua extends Dog { ... }
    class Dog extends Animal { ... }
    class Animal { ... }
    

    and construct an instance of the Chihuahua

    new Chihuahua()
    

    Java follows up the chain of inheritance and calls the parent constructors in the following order

    1. Object
    2. Animal
    3. Dog
    4. Chihuahua

    Before an object can be constructed, Java first has to construct its parent base.


    Object - the end of inheritance

    And if so, how deep can that go/how deep does it go?

    It always goes up the full inheritance tree. Which always ends with the all-father-class Object. Either by explicitly extending it

    class Foo extends Object { ... }
    

    or by implicitly exending it, if you do not write anything

    class Foo { ... }
    

    Object is a special class, it has no further parents and marks the end of each inheritance chain.