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.
Though it was a old post I came across this concept thought worth sharing it
Since we are talking about instance block here is how instance code flow executes in parent child relation class // Child extends Parent If we create a object for Child
1) Identification of instance members of the class from parent to child
2) execution of instance variable assignments and instance blocks only on parent class
3)execution of parent constructor
4)execution of instance variable assignments and instance blocks only on Child class
5)Execution of child constructor
Actually, it is like that.
Every instance of a subclass implicitly contains an instance of its superclass.
A superclass constructor is always invoked as the first step in any constructor (and that in turn runs any instance initializer blocks for the superclass)
After compilation instance init blocks become part of constructors.
javac
simply adds the init block to each constructor, that is this:Is equivalent to this:
So the init block runs when constructor runs.
Because there is always an implicit
super()
call(if not done explicitly) to the parent's constructor in the constructor of the child.