Constructor Chaining
Home ] Up ] An Example ] Points to Notice ] [ Constructor Chaining ] Superclass Method Calls ] Finalizer Chaining ]

 

 

Within a subclass constructor, the syntax:

super( /* arguments */ );

calls the appropriate constructor for that subclass's superclass.

  • This syntax is only valid within a subclass constructor
  • It must be the first statement within the body of the constructor
  • It is analogous to the syntax for one constructor of a class to call another constructor of the same class:
    this( /* arguments */ );

This is called constructor chaining.

  • If the first statement in a constructor is not an explicit call to a superclass constructor with the super keyword, then Java implicitly inserts the call:
super();

In other words, a call to the superclass's default constructor.

If the superclass does not have a default (zero-argument) constructor, it causes a compilation error.

  • There is one exception to the rule about implicitly inserting super():
  • If the first line of the subclass constructor uses the syntax:
this( /* arguments */ );

to call another constructor within the subclass, then Java relies on the second subclass constructor to invoke the superclass constructor (directly, or indirectly)

Other Calls to Superclass Methods

Within any subclass method, the syntax:

super.method( /* arguments */ );

calls the appropriate method for the superclass.

We saw this in the Manager class's raiseSalary method when it called the Employee class's raiseSalary method.

 

This page was last modified on 02 October, 2007