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.

Superclass Method Calls

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.

    public void raiseSalary(double byPercent)
    {
        // Add 1/2% bonus for every year of service
        Date today = new Date();
        double bonus =
                0.5 * (today.getYear() + 1900 - getHireYear());
        super.raiseSalary(byPercent + bonus);
    }

Question: What would be the result of omitting the super. prefix, as in:

    public void raiseSalary(double byPercent)
    {
        // Add 1/2% bonus for every year of service
        Date today = new Date();
        double bonus =
                0.5 * (today.getYear() + 1900 - getHireYear());
        raiseSalary(byPercent + bonus);
    }

???

Finalizer Chaining

You might think that, because Java enforces constructor chaining, that it would enforce finalizer chaining — in other words, that a finalizer method for a subclass would automatically invoke the finalizer method for the superclass.

Java does not do this. You must do this explicitly, if you write a subclass finalizer method, and if you want this behavior.

Usually, the code will look as follows:

protected void finalize() throws Throwable
{
    /* ... */
    super.finalize();	// Typically the last line of the method...
}

Again, do not think of a finalize method being equivalent to a destructor (as in C++), or something that can be used as some kind of Java “deconstructor”.  In most cases, if you think along those lines, you will get into trouble!