What is Constructor in Java with Example – Constructor Chaining and Overloading (original) (raw)
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
Here 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 classConstructorDemo{
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 voidmain(String args[]) throws IOException {
ConstructorDemo d = newConstructorDemo(); //calling no argument constructor in java
ConstructorDemo e = newConstructorDemo("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 objectby 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 constructorinside 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 reflectionand 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 privateconstructor.
6. Can Constructor be abstract, static, or final in Java
Constructor in Java can not be abstract, static,finalor 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 Encapsulationbecause 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