Constructors in Java
It
can be tedious and sometimes nightmares to initialize all variables in a
class each time an instance is created. It would be simpler to have all
the initialization done at the time of object creation itself. As the
initialization is so common Java allows objects to initialize themselves
whenever they are created. This automatic initialization of the object during creation is done by a special function called as constructor.
So as the above syntax
shows , the constructor is a specialized method of a class which has
the same name as the class name and the constructor gets automatically
gets invoked whenever an object of the class is created and is used to
initialize the private data members.
Now, consider a small program which includes the creation of object "obj" of class Printing.
In the above program, when the control encounters the new keyword memory for the new object is allocated and the constructor immediately creates and initializes the object of Printing Class.
Need For Constructors
In general it is best that all the objects are initialized when they are ceated.
However sometime we cannot initialize the object as we initialize the primitive members.
Consider the simple program given below which try to initialize the fields of class Car just as same as initializing the primitive data types.
In the above programs we can see that java gives an error when we try to initialize "obj1" . So to initialize the members or fields for an Object we use Constructors.
The functioning of the constructor and more programs involving constructors will be discussed in the next post.



No comments:
Post a Comment