Constructor in Java: Types, Uses, Example

A constructor in Java is a block of code, syntactically similar to a method that is used to initialize the state of an object in a class.

In other words, a constructor is a special member function of a class used to initialize instance variables of a class. The sole purpose of a constructor is to perform the initialization of data fields of an object in the class.

Java constructor can perform any action, but specially designed to perform initializing actions, such as initializing the instance variables with legal initial values.

A constructor within a class allows constructing the object of the class at runtime. It is automatically invoked when an instance of a class is created using the new operator.

Constructors can also accept arguments like methods and can be overloaded. If we try to create an object of the class without specifying any constructor in the class, the compiler automatically creates a default constructor for us.

Syntax to Declare Constructor in Java


Generally, we declare a constructor inside the public section of the class by the following syntax so that we can create its object in any function. The general syntax to declare a constructor in Java is as follows:

Access modifiers_name class_name(formal_parameter_list) // constructor header.  
{   
// Constructor body which is a block of statements.
// Here, we can initialize the values of instance variables.  
}

The following example code defines a constructor in the class.

public class Rectangle
{
  public Rectangle()  {    
    // constructor code goes here. 
  }
}

Here, Rectangle is a class name that must be the same as the name of class that contains constructor. That’s mandatory.

public is an access modifier that indicates that other classes can access the constructor. A constructor can be declared (optionally) as public, protected, and private. These are called access modifiers in Java.

Non-access modifiers cannot be applied with constructors in Java. By mistake, if you apply any other modifiers with constructor except these three access modifiers, you will get a compile-time error.


Note:

If you apply a private access modifier with a Java constructor, you cannot create an object of that class in other classes. If somebody asks that I want to create a class but nobody should instantiate it, you can say “make the constructor private”.

Characteristics of Java Constructor


There are the following characteristics or features of constructor in Java. They are as follows:

1. Constructor’s name must be exactly the same as the class name in which it is defined. It must end with a pair of simple braces.

2. The constructor should not have any return type even void also because if there is a 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.

It is a common mistake to declare the void keyword before a constructor. For example:

public void Rectangle() {

}

Here, Rectangle() is a method, not a constructor.

3. Java constructor may or may not contain parameters. Parameters are local variables to receive value (data) from outside into a constructor.

4. A constructor is automatically called and executed by JVM at the time of object creation. JVM (Java Virtual Machine) first allocates the memory for variables (objects) and then executes the constructor to initialize instance variables.

5. It is always called and executed only once per object. This means that when an object of a class is created, constructor is called. When we create second object, the constructor is again called during the second time.

6. Whenever we create an object/instance of a class, the constructor automatically calls by the JVM . If we don’t define any constructor inside the class, Java compiler automatically creates a default constructor at compile-time and assigns default values for all variables declared in the class.


The default values for variables are as follows:

a. Numeric variables are set to 0.
b. Strings are set to null.
c. Boolean variables are set to false.

7. In Java, constructors also provide thread safety, meaning no thread can access the object until the execution of constructor is completed.

8. We can do anything in the constructor similar to a method. Using constructors, we can perform all initialization activities of an object.

How to Call Constructor in Java


There are the following ways to call a constructor in Java.

1. A a = new A(); // Here, A is name of class.
2. new A(); // It is calling A() constructor.
3. super();
4. this();
5. class.forName(“com.scientecheasy.A”).newInstance();

When we create an object of class by using new keyword, a constructor is automatically called by Java Virtual Machine (JVM). After creating the object of the class, we cannot call the constructor again.

Consider the following example where we have created an object of a class School.

School sc = new School(); // Here, default constructor will call.

From the above syntax, you keep the following points in mind. They are:

  • School is the name of the class.
  • sc is an object reference variable which stores the address of the object in the stack memory.
  • School() is a constructor of class.
  • new is a special keyword that allocates the memory to store objects whose type is specified by a constructor. After allocation of memory, it calls constructor to initialize objects, which are stored in the heap ( a region of memory for storing objects).

When the constructor ends, a new keyword returns memory addresses to the object so that it can be accessed from anywhere in the application.

Types of Constructors in Java


Basically, there are three types of constructors in Java programming. They are as:

  1. Default Constructor
  2. Non-parameterized constructor
  3. Parameterized Constructor

Let’s understand the default, non-parameterized, and parameterized constructors with the help of some interesting examples.

Default Constructor in Java with Example


A constructor that has no parameter is known as default constructor in Java. When a class does not declare a constructor, Java compiler automatically adds a constructor for that class.

In other words, the compiler adds a default constructor only when we do not define any constructor explicitly. The constructor added by compiler is called default constructor. Look at the example in the below figure to understand better.

Default constructor automatically added by Java compiler in the classWe cannot pass any argument to default constructor. That’s why, it is also known as a no-argument constructor in Java. It does not do anything, but it allows to create an instance of class.

Features of Default Constructor


There are the following features of a default constructor in Java. They are as:

(1) When Java compiler adds a default constructor, it also adds a statement called super() to call the superclass constructor.

(2) Default constructor does not accept any argument value and has no statements in its body except super() statement. Sometimes, the call to superclass constructor within the default constructor may cause a compile-time error.


(3) A default constructor automatically initializes instance variables with default values. For example, string is initialized by null value.

(4) It has no throws clause.

(5) The access modifiers of the default constructor should be the same as the access modifier of the class. For example, if the top-level class is declared public, the default constructor should implicitly be declared as public. For example:

public class Student {
  String name;
}
is equivalent to declaration:

public class Student {
  String name;
  public Student() {
     super();
  }
}

Here, the default constructor is public because the top-level class is public.

Default Constructor Examples


Let’s take an example program where we will not create any constructor in the class. But Java compiler will automatically put a default constructor in the class. The default constructor will set default values to instance variables.

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.

Example 1:

package constructorProgram; 
public class Person 
{ 
 // Declaration of instance variables. 
    String name; 
    int age; 
    String address; 

 // Here, we are not creating any constructor. 
 // So, Java Compiler will automatically insert a default constructor. 
 // Create a user-defined 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 an object of class using new keyword. 
      Person p = new Person(); // Calling default constructor. 

   // Call display() method using object reference variable p. 
      p.display(); // Calling display method. 
   } 
}
Output: 
        null 0 null

Explanation:

In the preceding example program, we have not created any constructor in the class Person. So, the compiler adds a default constructor inside class. null, 0, null is the default values of the instance variables provided by the default constructor.

Non-parameterized Constructor in Java


A constructor which has no parameters in the parentheses but contains statements inside its body is called a non-parametrized constructor. We also call it as a non-argument constructor in Java.

A non-parameterized constructor has the same signature as that of default constructor, except for only one difference between them. Using non-parameterized constructor, we can initialize any values for the instance variables.

Let’s take an example program in which we will initialize different values to instance variables using non-parameterized constructor.

Example 2:

package constructorProgram; 
public class Person 
 { 
// Declaration of instance variables. 
   String name; 
   int age; 
   String address; 
// Declare a non-parameterized constructor. 
   Person() 
   { 
  // Initializing values to instance variables. 
     name = "Vivek"; 
     age = 25; 
     address = "Gandhi Nagar"; 
  // Print the values on the console. 
     System.out.println(name+ " " +age+ " " +address); 
   } 
// Main method. 
   public static void main(String[] args) 
   { 
   // Create an object of the class. 
      Person p = new Person(); // Calling default constructor. 
   } 
}
Output: 
        Vivek 28 Gandhi Nagar.

An example to show how Java constructor initializes values of variables inside the memory location

Let us see the memory detail behind the constructor. The above figure shows how to initialize values of variables inside the memory location.

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


Note: A reference variable never contains an object directly. It contains an address that points to data stored in the memory location.


In the above figure, you can see that when we did not initialize values of instance variables in the constructor in the example 1, default values for variables have been stored on the heap after calling constructor.

But, when we have initialized values of variables in the constructor in example 2, after calling the constructor, default values are eliminated from the memory location and initialized values are stored in the memory location of heap.

Parameterized Constructor in Java with Example


A constructor that takes one or more parameters and contains statements inside its body is called parameterized constructor in Java. In the parameterized constructor, instance variables automatically initialize at runtime when we pass values to parameters during object creation.

The parameterized constructor is used to provide different values to distinct objects. It allows us to initialize instance variables with unlike values. In the case of the default constructor, values remain the identical for all objects.

An example of parameterized constructor in Java program is as follows:

Person(String name, int age) {
 // Constructor code.
}

To call the parameterized constructor, we need to pass arguments while creating the object. Therefore, parameterized constructor is also called argument constructor in Java.

The argument can be of any type like integer, array, character, or object. It can take any number of arguments. Java does not provide a parameterized constructor by default.


Note: In Java, we cannot define two constructors in the same class with the same number of parameters of the same types in the same order.


Let’s consider an example program where we will define default, one parameter, and two parameter constructors and call them with passing arguments.

Example 3:

package constructorProgram; 
public class Demo 
{ 
// Declare non-parameterized constructor. 
   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 class. 
   Demo d = new Demo(); // Calling Default constructor. 
        d = new Demo(20); // Calling one argument constructor. 
        d = new Demo(10,15); // Calling two arguments constructor. 
   } 
}
Output: 
       Zero argument constructor 
       One argument constructor 
       Two arguments constructor

Explanation:

a. When JVM will execute the statement Demo d = new Demo(); it will call default constructor for class.

b. In the next line, JVM will call one argument constructor while executing of new demo(20).

c. The next line new Demo(10,15) will call two arguments 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);

Let us consider another example program in which we will initialize values to the instance variables in two manners. Look at the program code.

Example 4:

package constructorProgram; 
public class Student 
{ 
// Declaration of Instance variables. 
   String name; 
   String schoolName; 
   int std; 
   String city; 

// We can initialize instance variables 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. 
  // '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 parameters is different from the name of the variables that we set. 
  // 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 an object of the class and pass values to the constructor. 
      Student s = new Student("Ankit", "RSVM", 12, "DHANBAD");

   // Call display method to print the output. If you don't call, display() method will not print output. 
      s.display(); 
   }
 }
Output: 
        Constructor called... 
        Ankit RSVM 12 DHANBAD

Constructor with Array of Objects


Let’s take an example program to understand the concept of constructor with an array of objects in Java.

Example 5:

package constructorProgram; 
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 the statement Hello[] h = new Hello[4]; is executed. Default constructor is called when h[i] = new Hello(); is executed.

Use of Constructors in Java


The use of constructor in Java is as follows:

  • The constructor is used to assign the default value of instance variables.
  • A constructor is used to initialize objects of a class and allocate appropriate memory to objects. That is, it is used to initialize the instance variables of a class with a different set of values, but it is not necessary to initialize.
  • 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 the initialization of instance variables.
  • Learn the use of private constructor in Java with examples

Difference between Constructor and Method in Java


There are the following difference between constructor and method in Java that is explained in the below table:

SNConstructorMethod
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 we don’t provide any constructor in the class, Java Compiler provides a default constructor for that class.Method is not provided by the compiler in any case.
4.Constructor’s name must be the same as the 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 of Constructor:

1. The task of a constructor in Java is to initialize instance variables of an object.

2. A constructor of class is automatically executed by JVM when an object is instantiated.

3. When an object of class is instantiated, the constructor is called before any methods.

4. If you declare your own constructor, you have to decide what values should be given to instance variables.

5. this and super keyword must be the first line in the constructor.

6. Constructor overloading is possible in Java, but overriding is not possible.

7. It cannot be inherited in the subclass.

8. A constructor can also call another constructor of the same class using ‘this’ and for argument constructor use ‘this(para_list).

9. A constructor is not a keyword in Java programming.

10. In Java, a constructor is the third possibility to initialize instance variables in a class.

⇐ Prev Next ⇒

Please share your love