Why We Use Constructor in Java?
In this section, we will learn why we use a constructor in Java and what is the purpose and need of the constructor. Along with this, we will also see the types of the constructor.
In Java, the constructor is similar to the method. The property of the constructor is that it must have the same name as the class name. It has no return type. We do not require to call the constructor manually. It automatically invokes implicitly during the instantiation.
In other words, a constructor is a method that is called at runtime during the object creation by using the new operator. The JVM calls it automatically when we create an object. When we do not define a constructor in the class, the default constructor is always invisibly present in the class. There are the following reasons to use constructors:
In short, we use the constructor to initialize the instance variable of the class.
Types of Constructors
There are two types of constructors in Java:
As the name suggests, it accepts arguments (parameters). The parameterized constructor is used if we want to dynamically initialize the instance variables with the specified values at the time of instantiation.
The default constructor does not accept any parameter. It is used if we want to initialize the instance variables with certain values. Every Java class has a default constructor, invisibly. So, we need not to define it, separately. Remember that the default constructor is removed from the class when we create a parameterized constructor.
Note: When we do not provide any constructor to a Java program, the Java compiler writes the default constructor on behalf of the programmer and compiles the program. It initializes the instance variables with the default values. For example, 0 for integer, 0.0 for float, and null for String.
Let's create a program and use the default and parameterized constructor.
In the Employee class, we have created two constructors one is the default constructor and the other is the parameterized constructor. The Employee class has two private variables namely, name and age. In the main method, we have instantiated the class and used both the constructors.
Enter the name of the employee: David Enter the age of the employee: 27 Show() method for the parameterized constructor: Name of the employee: David Age of the employee: 27 Show() method for the default constructor: Name of the employee: William Age of the employee: 28