Constructors are special kind of methods that initialize a new object of the class. A constructor of a class is invoked when an instance of the class is created using the keyword new
.
Constructors have some differences from other methods:
they have the same name as classes containing them;
they have no return type (even
void
).
Constructors initialize instances (objects) of the class. They set values to the fields when the object is created. Also, constructors can take parameters for initializing fields by the given values.
Using constructors
Here is a class named Patient
. An object of the class has a name, an age, and a height. The class has a three-argument constructor to initialize objects with values.
class Patient {
String name;
int age;
float height;
public Patient(String name, int age, int height) {
this.name = name;
this.age = age;
this.height = height;
}
}
The Patient
constructor takes three parameters. To initialize the fields, the keyword this
is used. It's a reference to the current instance of the class. Use of the keyword is required only if parameters have the same name as the fields (to separate them).
Let's create some instances of the class using the written constructor.
Patient patient1 = new Patient("Heinrich", 40, 182.0f);
Patient patient2 = new Patient("Mary", 33, 171.5f);
Now we have two patients with the same fields, but different values.
Default and no-argument constructor
The compiler automatically provides a default no-argument constructor for any class without constructors.
Let's see an example.
class Nothing {
// the class has default no-argument constructor
}
We can create an instance of the class Nothing
using the no-argument default constructor:
Nothing nothing = new Nothing();
If you will define a constructor, the default constructor will not be created.
Sometimes explicit no-arguments constructor initializes fields of a class by "default" values (for example "Unknown" for a name).
Here is an example:
class Patient {
String name;
int age;
float height;
public Patient() {
this.name = "Unknown"; // sometimes, it may be better than null as the default value
}
}
To sum up
Any Java class has a constructor to initialize objects;
A constructor has the same name as the class containing it;
A constructor has no return type, even
void
;If a class has no explicit constructors, the java compiler automatically provides a default no-argument constructor.