Incremental Java
Constructors and Inheritance

Can't Inherit Constructors

You can't inherit constructors. Those have to be written. Why? Because the constructor name is based on the class name. When you inherit methods, the method signature must be the same. Constructors of a child class can't keep the same method signature of the parent class.

Constructors of Child Class Call Constructors of Parent Class

You've written a constructor for ColorRectangle, a child class of Rectangle.

What happens when the constructor is run? You would think it runs the code in the method body of the constructor. But something else happens first.

The code in the constructor for Rectangle is run.

Why?

Remember, you don't have access to the private instance variables of Rectangle. Also, Java really, really wants to initialize all variables in an object. So, the best way to do this is to call the constructor in Rectangle.

But which one?

The obvious choice is also the correct choice. The default constructor of the parent class is called. If the parent class also has its own parent class, then that constructor is also called, and so forth. In effect, the ancestor that's furthest up has its constructor called all the way down to its descendant and finally to the code in the method body of the constructor you called.

Calling Other Constructors

Java allows you to call other constructors beside the default one. This is how you do it:
public class ColorRectangle extends Rectangle
{
   Color color ;

   public ColorRectangle( int initWidth, int initHeight, Color initColor ) 
   {
       super( initWidth, initHeight ) ;
       color = initColor ;
   }
}
You can call the method super. This is really a call to the constructor of the parent class. Thus, the parent class (in this case, Rectangle) must have a public constructor that takes two int parameters.

Why super?

It's not like you can call the constructor directly.
public class ColorRectangle extends Rectangle
{
   Color color ;

   public ColorRectangle( int initWidth, int initHeight, Color initColor ) 
   {
       // NO! Creates a new Rectangle object!
       new Rectangle( initWidth, initHeight ) ;
       color = initColor ;
   }
}
This makes a completely new object. You can't call Rectangle( initWidth, initHeight ) without the new. Java designers could have let you do this, but they decided you should use super() with arguments, instead.

super must be called first

If you're going to call a non-default constructor, you must make it the first statement in the method body. The rule of thumb is: initialize parent class before you initialize yourself.

Initialize Parent Class Before You Initialize Yourself

It's only respectful. In any case, that's what Java does (and C++, for that matter)