Default Constructor#

All the constructors we have seen so far in this text have parameters. Sometimes we want constructors without parameters. These are called default constructors. For any class we can write any number of constructors, but they all need different numbers or types of parameters, that is different signatures. The signature of a default constructor is the class name, followed by empty parentheses.

When writing constructors for a class, it is best to write them starting from the most specific (maximum number of parameters) and going to the more general (no parameters). A goal is to avoid code repetition between constructors. For example, if we write the default constructor last, we should call a previous constructor to initialize each object, assuming such a constructor exists. (Sometimes we will only write a default constructor.) Let’s look at the example of the Square. The constructor we wrote takes an initial length value and builds a square of that size. If we want to supply a default constructor, which makes a default square of size 1 X 1, the code is as follows:

public Square(){
   this(1);
}

The use of the word this() with the parentheses refers to a constructor for “this” class. In our case, the non-default constructor takes one parameter, hence this() takes one parameter.

super, super(), this, this()

These four are all different - be cautious!

  • super is used to force traveling up the hierarchy.

  • super() calls the constructor, one level up the hierarchy.

  • this is used to reference attributes of the current object.

  • this() calls a constructor at the current level.

Practice Questions#

  1. Write a default constructor for the Rectangle class, that makes a rectangle of size 1 X 2.

  2. Write a default constructor for the RightTriangle class (see Chapter 2), that makes a right triangle with base 2 and height 5.

  3. Write a default constructor for the Circle class (see Chapter 2), that makes a circle with radius 1.

To Solutions