Tuesday, August 17, 2021

What is Constructor in Java with Example – Constructor Chaining and Overloading

What is constructor in Java
Constructor in Java is a block of code which is executed at the time of Object creation. But other than getting called, Constructor is entirely different than methods and has some specific properties like name of the constructor must be same as name of Class. Constructor also can not have any return type, constructor’s are automatically chained by using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted in Constructor. Similar to the method you can also overload the constructor in Java


In this Java tutorial, we will some important points about constructor in Java which is worth remembering for any Java programmer.

It’s also worth remembering that any static initializer block is executed before constructor because they are executed when class is loaded into memory while constructors are executed when you create an instance of any object e.g. using new() keyword.

Constructor in Java – things to remember

What is Constructor in Java with exampleHere are some important properties of constructor in Java, these are very specific to constructor only and does not apply to any other function or method.

1.  How to declare Constructor in Java

The first and most important rule of declaring a constructor is that name of constructor in Java must be exactly the same as the class on which you declare constructor, if it doesn't then the compiler will flag an error.  

A class in Java can have as many constructors as it and that is called constructor overloading in Java but the signature of two constructors must not be the same. here is an example of having multiple constructors in Java and how they are called using new() operator:



public class ConstructorDemo{
   public ConstructorDemo(){
      System.out.println("Inside no argument constructor");
   }
     
   public ConstructorDemo(String name){
      System.out.println("Inside one argument constructor in Java with name: " + name);
   }

   public static void main(String args[]) throws IOException {
     
     ConstructorDemo d = new ConstructorDemo(); //calling no argument constructor in java
     ConstructorDemo e = new ConstructorDemo("Testing"); //calling one argument constructor in java
 
   }
}

Output:
Inside no argument constructor
Inside one argument constructor in Java with name: Testing


In the above example, we have created two separate object by calling two different constructors of the class ConstructorDemo. If you notice carefully name of the constructor is same as the name of the class. Also signature of the two constructors is different from each other.


2. Constructor and Return Type

Another important rule of declaring a constructor is that constructor in Java doesn't have a return type. As I said constructor is different than methods in Java and doesn't return anything, Java Constructors are by default of type void. 

Though you can have a return statement inside the constructor without returning any value but can return control back to the caller. See the difference between method and constructor in Java for more differences.


3. Default and No Argument Constructor

Here comes another interesting property of constructor which is tested in SCJP and various other Java Exams and Java Interviews. Every Class in Java has constructor, if no explicit constructor is specified by Programmer, Java Compiler inserts a no argument constructor inside class. This is also called default Constructor in Java

if you provide any constructor in Java e.g. with one argument or two argument than compiler will not add default constructor or no arguments constructor, which makes your class unusable with framework or library which uses reflection and follow Java Bean naming convention. So always provide no argument constructor in Java. 

Another drawback of not providing no argument constructor is chances of having restricted hierarchy. Suppose another sub class is created and you don't add constructor over there than compiler tries to create a default constructor which calls super() at first line. 

super() means call to no argument constructor of super class and since there is no such constructor in your class it will fail with compilation error. This is like making your class final in Java.

4.  Constructor Chaining

One more important property of constructor in Java is constructor chaining. Calling one constructor from another constructor in Java is called Constructor chaining. you can use the keyword this for calling the constructor of the same class and keyword super for calling the constructor of the superclass. 

Anyway, call to the constructor must be on the first line of any constructor or else you will get a compilation error. Read more about constructor chaining and constructor overloading here.

5. Constructor and Access Modifiers

You can use any access modifier with a Java constructor. they can be public, protected or private. The default or no-argument constructor has the same access modifier as the class. You can also prevent a class from extension by making their constructor private

With private constructor instance of that class can only be created inside declaring class. Singleton pattern in Java is a popular example of a Class with a private constructor.


6. Can Constructor be abstract, static, or final in Java

Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructors.

7. Order of Initialization 

Since parent class is initialized before child class in Java, The constructor of parent class is executed before the constructor of the child class, that explains why super() is the first statement in default no argument constructor. To understand more about how the class is loaded into memory read How ClassLoader works in Java and When class is loaded and initialized in JVM.



8. Constructor and Exception

A constructor can throw Exception in Java in fact constructor can declare Exception in their throws clause but that makes the caller handle or re-throw Exception while creating any instance of Class.

9. Constructor vs Factory Pattern

Creating an object using new() keyword and constructor has there pros and cons. It's not good in terms of Encapsulation because if you directly create any instance of class you code is tied up with the structure of Constructor and any change in the constructor will require changes in all places where its object gets created. The standard way is to use factory design pattern in Java which encapsulates object creation logic and provides better maintenance over time.

10. Destructor

Unlike C++ there is no destructor in Java. Though objects have a finalize method which supposes to run before objects get garbage collected but that is not guaranteed by Java language specification and it may run or may not.

That’s all on What is constructor in Java and important points about constructor in Java. As you see there is a lot of rules and specific information around constructor but its an important aspect of the Java programming language and you must have a good grasp of all constructor specifics in Java. We have also touched on concepts like constructor chaining and constructor overloading which is quite popular on various Java exams.


Other Java design pattern articles from Javarevisited

7 comments :

Anonymous said...

What is default constructor in Java ? does default and no argument constructor is same? When will compiler inject default constructor and when it does not ?

Vermilion said...

Nice article...but can u tell me further
a)why do we need to include constructor in the class and
b)how important it with example...

thank you...

Anonymous said...

Every class atleast has one constructor whether u creat it or not when u not creat constructor compiler creat it by default...constructor is nothing it jst reserved the memory

neyo9999 said...

@Anonymous:Default Constructor in Java is the no argument constructor. Compiler will invoke the default constructor when no specified/parameterized constructor is used for instantiation. A constructor is always invoked the new keyword is executed & completed. Constructor extends the Object class.

Anonymous said...

If v want tobperform any operation predifindly dan v can use constructor. For eg.if i want to give any welcome message to user at that tym i can use construcor by writing dat message in constructor . Its advntage is that we dnt need to cal any method for this since costructor is calld at d tym of obj creation

MILKY SAHU said...

"Default or no argument
constructor has same access modifier as class" - what do you mean??

Nandan747 said...

" Since Constructor is used to create object"- this is where i had to stop reading further-
Constructors DO NOT CREATE OBJECTS. Its the new operator that does that job, everything you do in a constructor is just setting up(ex, states of object) and making the object ready to use

Post a Comment