Thursday, May 12, 2011

Constructor Chaining

We know that constructors are invoked at runtime when you say new on some class type as follows:
Sparrow sparrow = new Sparrow();

Now we will see what really happens when we say new Sparrow()?
(Assume Sparrow extends Bird and Bird extends Object.)
  1. Sparrow constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(), unless the constructor invokes an overloaded constructor of the same class (more on that in a minute). 
  2. Bird constructor is invoked (Bird is the superclass of Sparrow).
  3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Bird extends Object even though you don't actually type "extends Object" into the Bird class declaration. It's implicit.) At this point we're on the top of the stack.
  4. Object instance variables are given their explicit values. By explicit values,we mean values that are assigned at the time the variables are declared,like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.
  5. Object constructor completes.
  6. Bird instance variables are given their explicit values (if any).
  7. Bird constructor completes
  8. Sparrow instance variables are given their explicit values (if any). 
  9. Sparrow constructor completes.
You can find below,  how constructors are working in call stack

  1. Object()
  2.  Bird() calls super()
  3.  Sparrow() calls super()
  4. main() calls  new Sparrow()

1 comment: