|Constructor in Java|
Constructor in Java:
Objects are created with new operator and with some method call.This method call is nothing but the constructor. Which is responsible for creating the object properly and all objects we create, must be given some initial values to the variables,they contains.We can do this by using a dot(.) operator to access the instance variables and then assign some values individually.But we really look at this approach, it is very tedious and manual intensive approach to work with the variables individually.Secondly we need to call a method of that class to provide values of the instance variables.
Java provides a simpler,cleaner and more concise way to initialize the instance variable while creating an object.The way is called use of constructor.
A constructor is a special method in java which is used to create or construct an instance of a class and initialize the member variables of the newly constructed object.Object construction enables java run time environment to respond to a call(to an object’s constructor to create an actual object and store it in memory). It is called just after the memory allocation for the object.It can be used to initialize the variables of the object to desired values or starting values at the time of object creation.It can be said that an object or instance of a class does not exist in memory until it’s constructor is called.
It is not mandatory to provide a constructor for a class.If no user defined constructor is provided,the compiler,during compile time, puts one, called as default constructor and initializes the variable with it’s default value.
For numeric data types variables are set to zero(0), for character datatypes the variables are set to ‘