Calling constructors from other constructors in the same class in Java

Is it possible to call a constructor from another constructor in the same class?

Yes it is possible using the keyword this, but the call to another constructor must be the very first call that is made in the current constructor, otherwise the compiler will complain.

Nested calls to constructors can be made as we will see further below.

This example below shows how this might look like when calling only one other constructor:

As mentioned above, the call to the other constructor must be the first call in the current constructor. The following would thus fail and will not even compile:

The last example shows how to call several nested constructors:

The output from the last example is:

A wombat is commonly found in Australia and it likes to eat grass

Search for more Java info on this site here:
Custom Search

Please type any questions here.