Skip to main content

Java Constructors

Constructor as the name suggests is used to construct something and here in case of JAVA it is used to construct the object of class.
This is the first point where the object is assigned memory in heap and its member variables gets initialized by default values.Whenever we create an object by using new() keyword,it internally gives call to the default constructor of class. Even if you don't declare the default constructor , java compiler provides automatically a default constructor.
Let us test this out with a example . We have created a java class Student.java with a test class TestConstructor.java as shown below  :

Student.java

TestConstructor.java
Here we have created a object of Student class at line 9 using new keyword. This gives call to the default constructor of Student class. Note that we have not defined the default constructor explicitly in Student.java . This is provided by java compiler internally. The equivalent code that java compiler provides is as below :
                       Student(){
                                       }

Below is the console output :

Console Output
From the above output , we can see that the default constructor has initialized the member variables id and name to their respective default values . For primitive value int , it is 0 and for String(Object) it is null.
One important point to note is that the first line of code in a constructor should always be a constructor call either to parent class constructor using super keyword or the same class constructor using  this keyword. super() gives call to default constructor of parent class. If we don't specify anything , a super() call is added by java compiler to the constructor.So the default constructor provided by java compiler actually looks like below :
                       Student(){
                             super();
                                       }

We can make use of the constructor to create our objects with some initial values instead of default as below :
Student.java
We have created a default constructor in our Student.java and set initial value of id and name fields to 10 and " Bhavya" respectively( lines 6-9) . This is verified from the console output shown above when we run our TestConstructor.java main class.So any Student class object will be created with these initial values.

Ever wondered how we are able to use this keyword inside constructor (lines 7-8). Has the object been created before the constructor is finished since this keyword corresponds to current Object?

The answer is Yes. The object has been assigned memory in heap .This is done by the implicit super() call to parent class constructor i.e the default constructor of java.lang.Object class. As we already discussed, first line of code in a constructor should be a  constructor call either to parent class constructor using super keyword or to the same class constructor using  this keyword . Here since this call has not been explicitly specified, java compiler has added super() call before line 7 .This is the reason you are able to use this keyword inside constructor. So the above code is equivalent to :
Student.java

Parameterized Constructors : We can also create constructors by defining some parameters into the constructor. This is useful to  create objects by different ways based on the parameters.In our current example , say we want to create a Student object with id or name or both , we can do so by creating the corresponding parameterized  constructor. This is explained in below code where we have created two parameterized constructors along with a default one:

Student.java
Now we will create a student object by making use of these constructors as shown :

TestConstructor.java
We have created 3 student objects at lines 10, 15 and 20 using the different constructors in TestConstructor.java .You must note here that whenever we are creating a object by calling new keyword , it is going to create the respective object by calling the suitable constructor it finds based on the parameters passed. The console output shows how the different flavors of constructors are creating objects as per requirements.One important point to note is that even in case of parameterized constructors the compiler adds a call to default constructor of superclass using super() . So in our case before line 7, 12 and 16 of Student.java , there is implicit super() call added by java compiler.

SPECIAL CASES IN JAVA CONSTRUCTORS:

  1. In case you have declared a parameterized constructor in your class, java compiler will not add the default constructor for you by itself. You will have to explicitly add the default constructor in this case. Lets us verify this by following code . We will create a Student class with one parameterized constructor and we will try to create the object of this class by calling default constructor using new() call in our TestConstructor.java . Let us see what happens here.

    Student.java

    TestConstructor.java
    When we try running this code , this will give a compilation error : The constructor Student() is undefined . This shows that default constructor was not added by compiler in this case and you have to declare it explicitly.
  2. Constructor Chaining 
    This is a very useful concept in Java Constructors. Basically this means you can call one constructor from other within the same class using this keyword or you can call the constructor of parent class using super keyword. There is also a implicit call to the super class default constructor from every constructor we define as already shown in the post. It is very important to take care of this implicit constructor chaining which is provided by Java while designing your code otherwise you may experience some unwanted situations . We will replicate one of the common problems that may arise if you don't take care of constructor chaining.
    We have created two classes Student and it's parent class Parent . Student class as already used in this post has a parameterized constructor with two parameters id and name. The Parent class has one property gender with a single parameterized constructor with parameter gender.Student class will extend Parent class using extends keyword . This is shown below :

    Parent.java    
    Student.java

     As you can see our eclipse is complaining at line 6 of Student.java and giving a compilation error . Let's see what is the error it is giving :
    Compilation Error in Student.java
    The error is self explanatory in the above screenshot, we are getting compilation error because the child class constructor i.e the constructor of Student class is giving call to Parent class default constructor and default constructor is not present in Parent class. Also note that compiler has not added a default constructor in Parent class since we have already added a parameterized constructor in Parent class. The call to parent class constructor is added implicitly by java compiler in Student class constructor before line 7 of Student.java .
    You need to take care of this constructor chaining while designing your code otherwise you may end up with such kind of errors.
  3. Deadlocks in Constructors :A deadlock is a situation where your code is struck and it cannot proceed ahead. This is primarily because of interdependency between resources where in one resource is waiting for other to finish and vice-versa.In constructors , it arises when first constructor is calling the second constructor and similarly second constructor calls the first . This leads to a recursive call and none of the constructor gets chance to finish. Java compiler is quite smart in handling this situation beforehand and gives a compilation error as shown below:

    Student.java

    Compilation Error Highlighted

    This shows you cannot call constructors in recursion since this may cause deadlocks . This is other point that needs to be taken care of while designing your code.
I hope this gives you enough clarity about the right usage and implications that may arise if you do not design your code as per the constructor requirements. In case you have any queries please drop your questions in the comments section.







Comments

Post a Comment

Popular posts from this blog

Deeper Insight Into Java Serialization

Sometimes when a object is serialized at one server and deserialized at other server i.e on different JVMs , deserialization may fall and you can come across  InvalidClassException . This seems to be quite weird. Right? This post is aimed at explaining the root cause of this issue and what should be the better approach while implementing  serialization . You can refer to my other blog on Serialization where we have learnt the serialization mechanism and how to implement serialization  in Java to get started on  serialization. Basically , when we serialize any object , the class metadata is also saved along with object's state which is used while that object is deserialized. One thing that is part of this metadata is  serialVersionUID . In my previous post , I told you that it is used for versioning. We will now see what does it actually mean . You must have seen that whenever you implement serializable interface , compiler gives you warning to generate  serialVersionUID( suid )

Serialization In Java - A Complete Guide

This post is aimed to explain the concept of serialization in depth taking into account all the ins and outs that are required to be known to a Java Developer. Basic Usage And Information : Serialization is a very powerful JAVA instrument aimed at saving only the state of a object not its behaviour. This can be used to exchange objects between different systems and networks as is the case in typical enterprise applications.In a way,we can say that we want the object to exist beyond the lifetime of a JVM. Serialization Mechanism : This involves basically below steps : Firstly the metadata related to serializable instance is written which includes name of class,length of class, number of fields,serialversionuid etc. This metadata is written recursively for superclass if any till it reaches to java.lang.Object superclass. This is helpful when deserializing the class. Once metadata is written, the actual data is written. This time it begins from superclass to main class.