In this tutorial, we will learn a very interesting and easy topic Constructor in Java and types of Constructor with example programs. A constructor is a special method which initializes an object. If we try to create an object of the class without specifying any constructor, JVM will create a constructor for us. Such a constructor is known as default constructor. Let's see in detail.

Constructor in Java


A constructor in Java is a block of code within a  class that allows constructing the object of the class at runtime. It is similar to a method that is invoked when an instance of a class is created using the new operator. The purpose of the constructor is to initialize the objects of the class. 
Key points to remember:
1. Constructor name must be the same as its name of the class in which it is declared and defined.
2. The constructor should not have any return type even void also because if there is return type then JVM would consider as a method, not a constructor. Compiler and JVM differentiate constructor and method definitions on the basis of the return type.
Suppose you define the method and constructor with the same name as that of the class name then JVM would differentiate between them by using return type.

3. Whenever you create an object of the class, the constructor will be automatically called by the JVM. If you don't define any constructor inside the class, the compiler automatically creates a default constructor at compile time and assign default values for all your variables in the class.
Constructor in java with example program, Types of constructor in Java.

Declaration of Constructor in Java


A constructor can be declared inside the class by the following syntax.
Syntax
      Access modifiers_name  class_name(Parameter_list) 
    { 
        // Constructor body which is a block of statements where you can initialize the values of instance variables, local variables, call the methods, and print output. 
           } 
For Example:
        public Rectangle(int l, int b) {
               length=l;
               breadth=b;
              }
The public is access modifiers that indicates that other classes can access the constructor. A constructor can be declared (optionally) as public, protected, and private. A rectangle is a class name that must be the same as the name of the class that contains the constructor. 
Key points: 
Any access specifiers can be applied to constructors. If private is applied to the constructor, you cannot create an object outside of the class. If somebody asks that I want to create a class but nobody should instantiate it, you can say constructor must be private. 

How to call a Constructor in Java


In Java, you can call a constructor with the following ways.
1. A a=new A();
2. new A();
3. super(); // super
4. this();   // this
5. class.forName("com.scientecheasy.A").newInstance();

When we create an object of the class by using the new keyword, a constructor is called. After creating the object of the class, we cannot call the constructor again.
Object creation has the following syntax:
         new constructor.
Consider the following example.
          School sc=new School();
 Where
          School ➝ name of the class.
              sc     ➝ Object reference variable which stores the address of the object in the stack memory.
          School() ➝ Constructor of the class.
          new     ➝ is a special keyword that allocates the memory to store the object whose type is specified by a constructor and then calls the constructor to initialize the object, which is stored in the heap( a region of memory for storing objects). When constructor ends, a new keyword returns memory addresses to the object so that it can be accessed from anywhere in the application.

Why we use Constructor in Java?


1. The constructor is used to assign the default value of instance variables.
2. It is used to initialize the instance variable of the class with a different set of values but it is not necessary to initialize. 
3. If you need to execute some code at the time of object creation, you can write them inside the constructor. Generally, it is used for initialization of instance variable.
4. The private constructor is used in single tone classes where the object of the class cannot be created outside the class. 

Types of Constructor in Java


1. Default Constructor (No-argument constructor)
2. Parameterized Constructor (Argument constructor)

Default Constructor in Java


A constructor which has no parameter is known as default constructor in Java. When a class does not declare a constructor, JVM automatically creates a constructor for that class. This constructor is called default constructor. We cannot pass any argument to the default constructor. That's why it is known as a no-argument constructor. It does not do anything but it allows to create the instance of the class.

Let's take an example to understand the default constructor concept.
Suppose we have a class 'Person'. A person has three major properties like name, age, and address. where the name, age, and address are instance variables declared inside the class.
Program source code 1:
    package scientecheasy; public class Person { // Declaration of Instance variables. String name; int age; String address; // Here, We are not creating any constructor. So Compiler will automatically insert a default constructor. // Create one method to print the default values. void display(){ System.out.println(name+ " " +age+ " " +address ); } // Static method or main method. public static void main(String[] args) { // Create the object of the class using new keyword. Person p=new Person(); // Calling default constructor. // Call the method using object reference variable p. p.display(); // Calling display method. } }

    Output: null 0 null
In the above example, we did not create any constructor. So, the compiler provides a default constructor. null, 0, null is the default values of the instance variables provided by the default constructor

Now we can use the default constructor to initialize the values of instance variables. Let's see a simple example program.
Program source code 2:
    package scientecheasy; public class Person { // Declaration of Instance variables. String name; int age; String address; // Declare a default constructor. Person() { // Initialization of values of Instance variables. name="Vivek"; age=25; address="Gandhi Nagar"; //Print the values on the console. System.out.println(name+ " " +age+ " " +address); } // Static method or the main method. public static void main(String[] args) { // Create the object of the class using new keyword. Person p=new Person(); // Calling default constructor. } }

    Output: Vivek 28 Gandhi Nagar.
Now let's see the memory detail behind the constructor. The below figure shows how to initialize the values of the variables inside the memory location.
Java Parameterized constructor

We know that p is an object reference variable which contains the address of the memory location of the object. Here, 5575 is the address on the stack where you can find other detail of the class like name, age, and address on this address.  

Key points:
A reference variable never contains an object directly. It contains an address which points to data stored in the memory location. 
In the above image, you can see that when we did not initialize the values of the instance variable in the constructor in program 1, Default values are stored on the heap after calling constructor but when we initialized the values in the constructor in program 2, After calling the constructor, default values are eliminated and initialized values are stored in the memory location of heap.

Parameterized Constructor in Java


A constructor which takes parameters is known as parameterized constructor or argument constructor. The parameterized constructor is used to provide different values to the distinct object. To call the parameterized constructor, we pass the arguments while creating the object. The argument can be of any type i.e Integer, array, character or an object. It can take any number of arguments. Java does not provide a parameterized constructor by default.
Key points: 
You cannot write two constructors with the same number of parameters and the same number of types.
For Example:
       School sc=new School("RSVM", 20, "Dhanbad"); // Calling three argument constructor.
Let's take a simple scenario.
Program source code 3:
    package com.constructor; public class Demo { // Declare parameterized constructor with zero argument. Demo(){ System.out.println("Zero argument constructor"); } // Declare parameterized constructor with one argument. Demo(int a){ System.out.println("One argument constructor"); } // Declare parameterized constructor with two arguments. Demo(int a, int b){ System.out.println("Two arguments constructor"); } public static void main(String[] args) { // Create an object of the class. Demo d=new Demo(); // Calling Default constructor. d=new Demo(20); // Calling one argument constructor. d=new Demo(10,15); // Calling two argument constructor. } }
    Output: Zero argument constructor One argument constructor Two arguments constructor
The second line in the main calls the default constructor for the class. In the next line, we have called the one argument constructor due to new demo(20). The next line new Demo(10,15) calls the two argument constructor. You can see in all the three lines in the main the same object reference variable has been used. We can also write above three lines of code in this manner:
    Demo d=new Demo();
    Demo d1=new Demo(20);
    Demo d2=new Demo(10,15); 

Program source code 4:
 In this example program, we will see the declaration of the parameterized constructor in two manners. Let's see in the below program.


    package constructor; public class Student { // Declaration of Instance variables. String name; String schoolName; int std; String city; // We can declare a parameterized constructor in two manners. // First manner: public Student(String name, String schoolName, int std, String city) { //Here, The parameter's identifier is the same as that of the variables name. It is permissible to do this in Java. // The 'this' refers to the current object, the '.'called attribute's identifier selects the variables name, schoolName, std, city from the current object. // The '=' is the argument's identifier. System.out.println("Constructor called..."); this.name=name; this.schoolName=schoolName; this.std=std; this.city=city; } // Second manner. public Student(String n, String scn, int s, String c){ // Here, The name of the parameter is different from the name of the variables that it sets. // Therefore, we don't need to refer to the current object with 'this'. name=n; schoolName=scn; std=s; city=c; } // Create a method to print the output. You can also print the output inside the constructor. void display(){ System.out.println(name+ " " +schoolName+ " " +std+ " " +city); } // main method. public static void main(String[] args) { // Create the object of the class and pass the values to the constructor. Student s=new Student("Ankit", "RSVM", 12, "DHANBAD");// Const. called. // Call the display method to get the output. If you don't call then display method will not give output. s.display(); } }

    Output: Constructor called... Ankit RSVM 12 DHANBAD

Constructor with Array of Objects


Let's take a simple program to understand this concept.
Program source code 5:
    package com.constructor; public class Hello { Hello(){ System.out.println("Hello Java"); } public static void main(String[] args) { // Create an array object. Hello[] h=new Hello[4]; for(int i=0; i < h.length; i++ ){ h[i]=new Hello(); } } }
    Output: Hello Java Hello Java Hello Java Hello Java
Here, It is important to note that the default constructor is not invoked when Hello[] h=new Hello[4]; execute. Default constructor is called when h[i]=new Hello(); executes.

Difference between Constructor & Method


SN Constructor Method
1 Constructor is a special type of method that is used to initialize the state of an object Method is used to expose the behaviour of an object.
2 It has no return type even void also. It has both void and return type.
3 If you don't provide any constructor in the class, Compiler provides the default constructor for that class. Method is not provided by the compiler in any case.
4 Constructor name must be same as name of the class. Method name may or may not be the same name as the class name.
5 The purpose of a constructor is to create an object of a class. The purpose of a method is to execute the functionality of the application.
6 They are not inherited by subclasses. They are inherited by subclasses.

Key points to remember


1. When you create an object, its constructor is called before any methods.
2. If you declare your own constructor, you have to decide what values should be given to the instance variables.
3. this and super keyword must be the first line in the constructor.
4. Constructor overloading is possible but overriding is not possible.
5. It cannot be inherited in the subclasses.
6. A constructor can also call another constructor of the same class using 'this' and for argument constructor use 'this(para_list).
7. A Constructor is not a keyword in Java.

Final words
Hope that this article has covered almost all important topics related to the Constructor in Java. We hope that you will have enjoyed this article. All the practical example programs are very important to make commands on the constructor for beginners.
Thanks for reading!
Next ➤ Java Constructor Overloading

⏪ Prev Next ⏩