The Constructor Function


As in C++, constructor functions inJava are used to initialize the instances of a class. They have no return type (not even void) and can be overloaded. You can have multiple constructor functions, each with different numbers and / or types of arguments. If you don't write any constructor functions, a default (no-argument) constructor (that doesn't do anything) will be supplied by the compiler.

If you write a constructor that takes one or more arguments, no default constructor will be supplied and therefore, an attempt to create a new object without passing any arguments will cause a compile-time error.

It is often useful to have one constructor call another. For example, a constructor with no arguments might call a constructor with one argument, passing a default value. This call must be the first statement in the constructor. It is performed using this as if it were the name of the method. For example:

this( 10 );

The above is a call to a constructor that expects one integer argument.

Initialization of fields:
If you don't initialize a field i.e. either you don't write any constructor function, or your constructor function just doesn't assign a value to that field, the field will be given a default value, depending on its type. The default values of different types of variables have been discussed in a previous lesson.