Constructors is a special mechanism using which, the member variables of an object can be initialized when the object is being created. Constructors also ensure that no object is created with missing or invalid data. e.g., Since every student should have a name, section and marks, we can restrict such that Student can only be created when all the required information is present and is valid.
class Student
{
String name;
int marks;
char section;
}
For a class
Student
, we need to do the following to initialize the member variables of the student object.
Student st1 = new Student();
st1.name = "Srini"; // LINE A
st1.marks = 78;
st1.section = 'C';
There is a chance, we might accidentally not initialize the variable
name
,
i.e. we forgot writing the code in
LINE A
, then the student will exist with out any name. Having student with out any name, is not a desirable situation. So we declare a constructor in the class
Student
as shown below. This constructor takes 3 parameters -
nameParam
,
marksParam
and
sectionParam
.
class Student
{
String name;
int marks;
char section;
// Constructor for student which takes 3 parameters.
Student(String nameParam, int marksParam, char sectionParam)
{
name = nameParam;
marks = marksParam;
section = sectionParam;
}
}
In the constructor, the passed values
nameParam
,
marksParam
and
sectionParam
are assigned to the member variables
name
,
marks
and
section
. Now the code for creating the
Student
object and initializing the variables is simplified as shown below.
Student st1 = new Student("Srini", 78, 'C');
- For every class, when there is no constructor defined, then a default constructor with no parameters is automatically created by the compiler. That is the reason, we were able to call
new Student();
even with out any constructor.
- If a constructor with parameters is defined in the class, then the compiler will not add any default constructor, which means we can not create any object using the default constructor. We have to use the constructor with parameters, to create the object. If we also want to support the default constructor, then we should also explicitly declare that in the class.
- We can have more than one constructor in a class. For e.g., for the Student class we can have one constructor which does not take parameters (default constructor), one constructor which takes only
name
, one constructor which takes both name
and marks
and one more constructor which takes name
, marks
and section
. The objects can be created using any one of the four constructors. This is further explained in Class With Multiple Constructors In Java.