Search code examples
javainheritanceinitializationinitialization-block

Instance initialization block and subclasses


I'm getting confused about when the instance initialization block should run. According to Kathy Sierra's book:

Instance init blocks run every time a class instance is created

So, consider having two classes: a parent and a child, according to this question and java's documentation:

instantiating a subclass object creates only 1 object of the subclass type, but invokes the constructors of all of its superclasses.

According to the above: why does the instance initialization block located in superclasses gets called every time an object of the subclass is instantiated? it isn't like that a new object of the superclass is instantiated.


Solution

  • After compilation instance init blocks become part of constructors. javac simply adds the init block to each constructor, that is this:

    public class Test1 {
        int x;
        int y;
    
        {
            x = 1;
        }
    
        Test1() {
            y = 1;
        }
    }
    

    Is equivalent to this:

    public class Test1 {
        int x;
        int y;
    
        Test1() {
            x = 1;
            y = 1;
        }
    }
    

    So the init block runs when constructor runs.