What is Constructor and Destructor in Java?
In Java, a constructor is a special method invoked when an object is created. It has the same name as the class and initializes the object’s state. Constructors are essential for setting up an object’s initial values and ensuring it is in a valid state. They can be parameterized to accept values during object creation.
On the other hand, a destructor is not explicitly defined in Java, as the Java Virtual Machine (JVM) automatically handles memory management through garbage collection. The garbage collector identifies and deallocates unused objects, eliminating the need for explicit destructors. Java developers don’t need to worry about freeing up memory manually, making the language more robust and secure than languages requiring explicit memory management. Instead of destructors, Java developers focus on writing clean-up code in methods like finalize(), which the garbage collector calls before an object is reclaimed.
Table of Contents
- Constructor and Destructor in Java
- Why We Need?
- How do Constructors and Destructors Work in Java?
- How to Create Constructor and Destructor in Java?
- Key Differences Between Constructor and Destructor
- Head to Head comparison between Constructor and Destructor
Why do we Need?
Constructor and destructor are mostly used to handle memory allocation and de-allocation efficiently. Constructor and destructor play a very important role in any programming language of initializing and destroying it after use to free up the memory space.
How do Constructors and Destructors Work in Java?
A constructor is just a Java method with the same name as the class name. The constructor method does not have any return type to it.
Look at the following example for more clarity:
class Employee {
Employee() {
}
}
As you see in the above example, we have not given any return type like int or void to the method, which has the same name as a class name.
It is mainly used to initialize the object. When creating an object of a class, the constructor gets invoked at that time.
It will be more clear with the following code snippet.
Compared to other programming languages, such as C++, Java doesn’t have explicit destructors. The responsibility of managing memory in Java is assigned to the garbage collector. The garbage collector automatically identifies and deallocates objects that are no longer referenced. Hence, there is no need for explicit destructor methods in Java compared to other languages.
How to Create Constructor and Destructor in Java?
Look at the following example
class Employee {
Employee() { //This is constructor. It has same name as class name.
System.out.println("This is the default constructor");
}
}
Types of Constructor
There are two types of constructors; depending on the type, we can add and remove variables.
- Default Constructor
- Parameterized Constructor
With this, we are also going to see constructor overloading.
1. Default Constructor
This is the one type of constructor. By default, without any parameters, this constructor takes place. This constructor does not have any parameters in it.
Example:
class Abc{
Abc(){
System.out.println("This is the example of default constructor.");
}
}
2. Parameterized Constructor
As the name suggests, the parameterized constructor has some parameters or arguments when initializing the object.
Example:
import java.util.*;
class Square{
int width,height;
Square(int a , int b){
width = a;
height = b;
}
int area(){
return width * height;
}
}
class Cal{
public static void main(String[] args){
{
Square s1 = new Square(10,20);
int area_of_sqaure = s1.area();
System.out.println("The area of square is:" + area_of_sqaure);
}
}
}
Output:
Now, it is time to talk about constructor overloading in Java. This means having multiple constructors with different parameters. So, with this, each constructor can do different tasks. Sometimes, as per the requirement, we need to initialize constructors differently.
Example
import java.util.*;
public class Main{
String name;
int quantity;
int price;
Main( String n1, int q1, int p1){
name = n1;
quantity = q1;
price = p1;
}
Main( String n2, int p2){
name = n2;
price = p2;
quantity = price/10;
}
void display(){
System.out.println("Product Name "+ name);
System.out.println("Product quantity is "+ quantity);
System.out.println("Product price is "+ price);
}
public static void main(String[] args){
Main product1;
product1 = new Main("Dates",500,50);
product1.display();
product1 = new Main("cashu",800);
product1.display();
}
}
Output:
Try the above program, and you will be clear about what is happening with constructor overloading.
Destructor
Before we start talking about the destructor, let me tell you there is no destructor in Java. Destructor is in C++ programming language. If we are talking about Java, Java has an automatic garbage collector feature, which frees the dynamically allocated memory when there is no use. This concept is very important, and you can explore this garbage collection in Java more.
- Java uses the garbage collection technique for memory allocation automatically.
- There is no need to explicit use of destructors like C++.
- We do not have a malloc function for allocating memory in Java like in C programming.
- The new operator in Java does the same process of allocating memory.
- new keyword allocates memory space for an object on heap memory.
- At the time of program execution, a new keyword allocates some memory space for the object. End-users need to worry about this as the program handles memory allocation. When the object used in programs is done with the work, the memory used for the object is utilized for another task. This process of utilizing memory efficiently is the job of garbage collection in Java.
Let’s talk about destructor; as we know, there is no destructor in Java as it has a finalize() method to do so. The following are some of the key points to be noted.
Finalize() Methods
- As we have seen earlier, the finalize method works like a destructor and the opposite of a constructor.
- Generally, the finalize method is used to remove the object.
- To use this method, we have to define this method in Java explicitly.
- The finalize method starts working after garbage collection is done with its work.
- This means that after freeing memory space by deallocating memory space from objects, there are chances that memory utilization is still there with other things like fonts, etc.. To delete that memory space or to free up that space, we use the finalize() method.
Key Differences Between Constructor and Destructor
There are several differences between constructors and destructors. Below are some of the common and important differences.
- The constructor is invoked when an instance of that class is created. It doesn’t need to be called explicitly. In the case of the destructor, it invokes when the instance of any class is deleted. It also comes in a role automatically right after the object is deleted.
- The constructor occupies the system’s memory by locating them to the resources, which is just the opposite in the case of the destructor. In the destructor, the memory assigned to the resources is released so that another resource can use it.
- To declare the constructor, there is no need for a special character. One can create a method whose name is similar to the class’s. In the destructor case, the tilde sign has to be used to introduce the program’s destructor.
- The constructor can be used in the high and middle-level programming language. While in the case of the destructor, it cannot be used in a high-level language. C++ can use the destructor, but the same is not available in Java. This is because high-level programming languages have a mechanism for memory management.
- The constructor can be used very often in the program. It is very simple to use and reduces the complexity of the program. On the other hand, the destructor is preferred to be used when the program resources need to reduce memory consumption.
Head to Head comparison between Constructor and Destructor
Constructor | Destructor |
Invoked while instance creation When the instance or object of any class is created, it leads to automatically calling the constructor, which will make all the statements under the constructor method to be executed. |
Invoked while instance deletion When the instance or object is deleted, the destructor is invoked automatically, and afterward, the statements of the destructor class are executed sequentially. |
Occupies memory While the class is invoked, it allocates memory to all the resources the class will use further. It leads to consuming the system’s memory to store the data on a permanent or temporary basis. |
Releases Memory While the destructor is invoked, it releases all the memories that the resources have been occupied. The released memory can be further located to other resources used in the program. |
Supported in mid and high-level languages The constructor is called automatically whenever an instance of that class has been created, and this feature is supported by both kinds of languages: Mid and high-level programming languages. |
Support only in middle-level language The features of the destructor are only supported in a middle-level language like C++. When it comes to high-level language like Java, it doesn’t allow features like this as it has its own way of managing the memory. |
No special character is required while the declaration To declare the constructor, one needs to write the method’s name, which must be the same as the class’s. There should be no special character required to declare a constructor. |
Tilde is used in a declaration. To declare the destructor, it will be required to use a tilde. The constructor’s name must be followed by the tilde sign and end with small brackets, as happens in every function. |
Conclusion
The constructor is nothing different but the method with the same name as the class’s. It takes no time to get invoked once the instances are created. In this case, the object can be created using the same syntax as it is used to create an object of any class. When the object is created, it occupies the memory space and brings the constructor’s statement into execution.
The destructor is something exactly opposite to that of the constructor. It is invoked immediately after the object is deleted. When the object is deleted, it deletes all the resources located to it, freeing up all the memories they reserved so that the new resources could use that memory. Though both concepts differ, they play a vital role in programming, especially when discussing efficient programming using middle-level language.
FAQs
Q1. How is a constructor different from a regular method?
Answer: Constructors have the same name as the class and do not have a return type, whereas methods may have any name and have a return type. Constructors are called implicitly when an object is created.
Q2. Can a class have multiple constructors?
Answer: Yes, a class can have multiple constructors. This is known as constructor overloading. Constructors can differ in the number or types of parameters they accept.
Q3. Can constructors be inherited?
Answer: Constructors are not inherited in the same way as other methods. However, a subclass constructor implicitly calls the constructor of its superclass using the super() keyword.
Q4. Can I force the execution of the garbage collector?
Answer: You can suggest garbage collection by calling System.gc() or Runtime.getRuntime().gc(), it does not guarantee immediate execution. The decision to run the garbage collector is ultimately up to the JVM.
Recommended Articles
We hope that this EDUCBA information on “Constructor and Destructor in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.