Wednesday, December 12, 2012

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

What is constructor in Java
Constructor in Java is 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 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 method you can also overload 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 remember 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 instance of any object e.g. using new() keyword.

Constructor in Java – things to remember

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

1) First and most important rule of declaring constructor is that name of constructor in Java must be exactly same with the class on which you declare constructor, if it doesn't then compiler will flag as error. A class in Java can have as many constructor as it and that is called constructor overloading in Java but signature of two constructor must not be 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 above example we have create two separate object by calling two different constructors of class ConstructorDemo. If you notice carefully name of constructor is same as name of class. Also signature of two constructor is different to each other.

2) Another important rule of declaring constructor is that constructor in Java doesn't have return type. As I said constructor is different than methods in Java and doesn't return anything, Java Constructor are by default of type void. Though you can have return statement inside constructor without returning any value but can return control back to caller. See difference between method and constructor in Java for more differences.

3) 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) 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 keyword this for calling constructor of same class and keyword super for calling constructor of super class. Anyway call to constructor must be on the first line of any constructor or else you will get compilation error. Read more about constructor chaining and constructor overloading here.

5) You can use any access modifier with Java constructor. they can be public, protected or private. Default or no argument
constructor has same access modifier as class. You can also prevent a class from extension by making there constructor private. With private constructor instance of that class can only be created inside declaring class. Singleton pattern in Java is popular example of Class with private constructor.

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

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

8) Constructor can throw Exception in Java in fact constructor can declare Exception in there throws clause but that makes caller to handle or re throw Exception while creating any instance of Class.

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

10) Unlike C++ there is no destructor in Java. Though objects has finalize method which suppose to run before objects gets 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 lot of rules and specific information around constructor but its an important aspect of Java programming language and you must have good grasp of all constructor specifics in Java. We have also touched concepts like constructor chaining and constructor overloading which is quite popular on various Java exams.

Other Java design pattern articles from Javarevisited

6 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??

Post a Comment