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.
For a class
, 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
we forgot writing the code in
, 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
as shown below. This constructor takes 3 parameters -
// 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
are assigned to the member variables
. Now the code for creating the
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
marks and one more constructor which takes
section. The objects can be created using any one of the four constructors. This is further explained in Class With Multiple Constructors In Java.