Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.
Whenever we use new
keyword to create an instance of a class, the constructor is invoked and the object of the class is returned. Since constructor can only return the object to class, it’s implicitly done by java runtime and we are not supposed to add a return type to it. If we add a return type to a constructor, then it will become a method of the class. This is the way java runtime distinguish between a normal method and a constructor. Let’s assume we have following code in Employee
class.
Here the first one is a constructor, notice that there is no return type and no return statement. The second one is a normal method where we are again calling the first constructor to get Employee instance and return it. It’s recommended to not have method name same as the class name because it creates confusion.
There are three types of constructor in java.
Let’s look into all these constructor types with example programs.
It’s not required to always provide a constructor implementation in the class code. If we don’t provide a constructor, then java provides default constructor implementation for us to use. Let’s look at a simple program where default constructor is being used since we will not explicitly define a constructor.
Constructor without any argument is called a no-args constructor. It’s like overriding the default constructor and used to do some pre-initialization stuff such as checking resources, network connections, logging, etc. Let’s have a quick look at the no-args constructor in java.
Now when we will call new Data()
, then our no-args constructor will be called. Below image illustrates this behavior, check the console output of the program.
Constructor with arguments is called parameterized constructor. Let’s look at the example of parameterized constructor in java.
When we have more than one constructors, then it’s constructor overloading in java. Let’s look at an example of constructor overloading in java program.
Note that we can’t use abstract, final, static and synchronized keywords with constructors. However we can use access modifiers to control the instantiation of class object. Using public
and default
access is still fine, but what is the use of making a constructor private? In that case any other class won’t be able to create the instance of the class. Well, a constructor is made private in case we want to implement singleton design pattern. Since java automatically provides default constructor, we have to explicitly create a constructor and keep it private. Client classes are provided with a utility static method to get the instance of the class. An example of private constructor for Data
class is given below.
When a constructor calls another constructor of the same class, it’s called constructor chaining. We have to use this
keyword to call another constructor of the class. Sometimes it’s used to set some default values of the class variables. Note that another constructor call should be the first statement in the code block. Also, there should not be recursive calls that will create an infinite loop. Let’s see an example of constructor chaining in java program.
I have overridden the toString() method to print some useful information about Employee object. Below is the output produced by above program.
Notice how one constructor is being called from another constructor, that’s called constructor chaining process.
Sometimes a class is inherited from a superclass, in that case, if we have to call superclass constructor then we can do it using super
keyword. Let’s have a look at an example of using super class constructor. Note that super constructor call should be the first statement in the child class constructor. Also when instantiating child class constructor, java first initializes the super class and then child class. So if the super class constructor is not explicitly called then default or no-args constructor is called by java runtime. Let’s understand these concepts through some example program. Let’s assume we have two classes like below.
Now if we create a Student object like below;
What will be the output produced? The output of the above code will be:
So the call went to the no-args constructor of Student class since there was no super call in the first statement the no-args or default constructor of Person class is called. Hence the output. What if we are using parameterized constructor of Student class as Student st = new Student(34, "Pankaj");
, the output will be:
Here the output is clear because we are explicitly calling superclass constructor, so Java doesn’t need to do any extra work from their side.
Java copy constructor takes the object of the same class as an argument and creates a copy of it. Sometimes we need a copy of another object to do some processing. We can do this by following ways:
Now let’s see how to write a copy constructor. Suppose we have a class Fruits
like below.
Notice that Fruits(Fruits fr)
is performing a deep copy to return the copy of the object. Let’s look at a test program to understand why it’s better to have copy constructor to copy an object.
The output of the above program is:
Notice that when copy constructor is used, both the original object and its copy are unrelated to each other and any modifications in one of them will not reflect into other. That’s all for the constructor in java.
Constructors play a crucial role in Java frameworks such as Spring and Hibernate:
Spring Framework: Uses constructor injection to enforce dependency management, particularly for immutable beans.
Hibernate ORM: Hibernate ORM uses default (no-argument) constructors to instantiate objects when retrieving data from the database. The default constructor is essential because Hibernate creates objects using reflection and needs a way to instantiate an entity before setting its properties.
A constructor in Java is a special method that initializes objects. It is automatically called when an object is instantiated. Unlike regular methods, constructors do not have a return type, not even void
. Constructors help in setting up initial values for object properties and ensure that an object is in a valid state from the beginning.
Java supports different types of constructors, which include:
Constructors and methods differ in purpose. A constructor is called automatically when an object is created, ensuring proper initialization. Methods, on the other hand, must be explicitly invoked and are used to define behavior. Additionally, a constructor cannot return a value, whereas methods can return results based on business logic.
Feature | Constructors | Methods |
---|---|---|
Purpose | Initialize objects | Define behavior |
Invocation | Automatically called | Explicitly invoked |
Return Type | No return type | Can return a value |
Overloading | Yes | Yes |
Overriding | No | Yes |
Access Modifiers | Yes | Yes |
Static | No | Yes |
Final | No | Yes |
Abstract | No | Yes |
Synchronized | No | Yes |
new
keyword.Feature | Constructors | Objects |
---|---|---|
Purpose | Initializes objects | Represents an instance of a class |
Creation | Executed once per object creation | Created using the new keyword |
Duration | Executes once | Persists in memory and can be used multiple times |
Role | Sets initial state of an object | Represents a real-world entity or concept |
Constructors provide multiple benefits, including:
Constructors are an essential part of Java programming, playing a crucial role in object initialization and class design. From simple default constructors to more advanced constructor chaining and dependency injection in frameworks like Spring and Hibernate, understanding how constructors work can help developers build robust, maintainable applications.
By leveraging constructors effectively, you can enforce immutability, promote reusability, and optimize performance.
You can check out these related tutorials to learn more:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Constructor does not have return type It’s implicit return type is void, but not current class. Constructor is only responsible for initializing object. Object is created and it’s reference is returned by new keyword. For proof you can check constructor bytecode by using javap -verbose command as javap -verbose Example You will find constructor declaration as Example()V --> V stands for void and end of constructor you will find only return–> means returning nothing
- Hari Krishna
But why are you using this below code ? @Override public String toString() { return "ID = “+id+”, Name = "+name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } what the purpose to write this code in the example… can you please explain ?
- vivek singh
Sir in the copy constructor, the code Fruits frCopy = fr; frCopy.getFruitsList(). add ( “Apple” ); We called the getFruitsList,it will return the list and we are adding a fruit.does it affect the object list.Can you explain it?
- Nithya sai