Home » Java Tutorial » Constructor in Java

Constructor in Java


Reading Time - 18 mins

A constructor in Java is nothing but a special method that is executed during instance creation of a class. Whenever we create an object for the class, the java compiler calls the constructor of that class implicitly. We can use the constructor to initialize arguments for the object which we use within the class. In this tutorial, we will also learn types of Java Constructors, Constructor Overloading, Constructor Chaining.

Creating a Constructor in Java

We can create a constructor in the following way. The constructor in Java has 4 parts:

  • Access modifier – Eg: public as in the below example
  • Constructor name – Eg: Employee
  • Arguments – Optional. Parameters to assign value to variables
  • Body of constructor – To assign values to the variables or any piece of code if required
public class Employee {


  public Employee()
  {
  //Body of constructor
  }
  public static void main(String[] args) {
    Employee e1 = new Employee();
  }
}

Working of a Constructor

As you can see in the above example, we have a class named “Employee” with a Constructor defined. In the main method, we create an object named e1 using a new keyword for the Employee class. When this line is executed, the java compiler invokes the Employee constructor.

Constructor in Java

Features of Constructor

  • A constructor in Java should have the same name as the class name.
  • It does not have any return type
  • It cannot be abstract, static or final

Types of Java Constructors

There are 3 different types of constructors in Java:

Types of Java Constructors

Default Java constructor

When we do not create any constructor in Java for the class, the Java compiler creates a default constructor. This code will not be visible to us in the java file but will be present in the .class file. It does not contain any code and the body of the constructor will be empty.

Constructor in Java

No argument constructor

When we do not pass any parameter to the constructor in Java, we call it a no-argument constructor. The main difference between default and the no-argument constructor is that here we define the constructor with empty arguments which is visible in the java file whereas default constructor code is not visible to us and will be created by the java compiler. Also in default constructor, the compiler creates an empty constructor while in the no-argument constructor, we can define any code for assigning values.

public class Employee {

  public Employee()
  {
    System.out.println("No argument constructor");
  }
  public static void main(String[] args) {
    Employee e1 = new Employee();

  }

}
No argument constructor

As we can see in the above example, when the object e1 is created, it invokes the constructor and prints the line of statement as output.

READ  Operators in Java

Parameterized Java constructor

When we pass parameters or arguments to a constructor in Java, we call it as a Parameterized constructor. We can use these arguments to assign values to the variables in the class.

public class Employee {
  int empid;
  String empname;
  public Employee(int id, String name)
  {
    empid = id;
    empname = name;
  }
  public static void main(String[] args) {
    Employee e1 = new Employee(102,"Ravi");
    System.out.println("Employee id: " + e1.empid);
    System.out.println("Employee Name: " + e1.empname);
  }

}
Employee id: 102
Employee Name: Ravi

In the above example, we are passing 2 arguments to the constructor which is the “id” of integer type and “name” of String type. Inside the constructor, we assign values to the class variables “empid” and “empname”. We can then access these 2 variables using the Employee object “e1”. When we create an object for the class, we pass the actual values to the constructor so that the compiler assigns values to these variables during initialization which means the variable “empid” will have the value 102 and the variable “empname” will have the value “Ravi“.

Exception in Parameterized constructor

Suppose we have a class with a parameterized constructor and we call a no-argument constructor during object creation. In this case, we get an exception, since the compiler searches for a no-argument constructor. The compiler will not create a default constructor in this case since we have defined a parameterized type.

We can see this example clearly in the below code.

public class Employee {
  int empid;
  String empname;
  public Employee(int id, String name)
  {
    empid = id;
    empname = name;
  }
  public static void main(String[] args) {
    Employee e1 = new Employee();
    System.out.println(e1.empid);
  }

}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The constructor Employee() is undefined

  at Employee.main(Employee.java:11)

Suppose we remove the parameterized constructor, then the compiler inserts the default constructor and does not throw any compilation error. It displays 0 since no value is assigned to the variable.

public class Employee {
  int empid;
  String empname;
  public static void main(String[] args) {
    Employee e1 = new Employee();
    System.out.println(e1.empid);
  }

}

Constructor Overloading

A class that has multiple constructors each with different parameter lists is known as Constructor overloading. This means each constructor performs different tasks based on the arguments. Let’s see an example below. Here, we have 3 constructors, one with no argument, second with parameters as int and String, and third with only String as an argument. Based on the object we create with the parameter list, the corresponding constructor will get executed.e1 object has no arguments, hence the default will be assigned to the variable which is 100. e2 has 2 arguments with values and hence these 2 values will be assigned to the corresponding empid and empname variables. e3 and e4 have only String argument and hence this will call the 3rd constructor which has the variable empRole.

READ  OOPs concepts in Java

The below program explain about constructor overloading.

public class Employee {
  int empId;
  String empName;
  String empRole;
  
  public Employee() {
    this.empId = 100;
  }
  
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
  public Employee(String designation) {
    this.empRole = designation;
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee();
    Employee e2 = new Employee(102,"Rakesh");
    Employee e3 = new Employee("Java Developer");
    Employee e4 = new Employee("Tester");
    System.out.println("Default value of Empid: " + e1.empId);
    System.out.println("Employee id: " + e2.empId + " " + "Employee Name:" + e2.empName);
    System.out.println("Employee Role: " + e3.empRole + " and " + e4.empRole);
    
  }

}

Default value of Empid: 100
Employee id: 102 Employee Name:Rakesh
Employee Role: Java Developer and Tester

Constructor Chaining

Calling one constructor from another constructor is called Constructor chaining. The main objective of this is that we can do initialization in one place and call many constructors with different parameters. We can achieve this by calling the other constructors using this keyword. For example, if we see in the below code, we call the no-argument constructor during object creation from the main method. From this constructor, we call another constructor by passing name and age parameters. This will call the second constructor and from here we call the third constructor by passing 3 parameters including berth. Hence finally, in the constructor, we initialize all the variables. Here we are creating a separate method named displayTicket to print all the above values.

Constructor Chaining

The below program explain about constructor chaining.

public class TicketBooking {
  String passName;
  int passAge;
  String passBerth;
  
  public TicketBooking() {
    this("Arun",45);
  }
  public TicketBooking(String name, int age) {
    this(name,age,"Lower berth");
  }
  public TicketBooking(String name,int age,String berth) {
    this.passName = name;
    this.passAge = age;
    this.passBerth = berth;
    
  }
  void displayTicket() {
    System.out.println("Passenger Name:" + passName);
    System.out.println("Passenger Age: " + passAge);
    System.out.println("Passenger Berth: " + passBerth);
  }
  public static void main(String[] args) {
    TicketBooking tb = new TicketBooking();
    tb.displayTicket();
  }

}
Passenger Name:Arun
Passenger Age: 45
Passenger Berth: Lower berth

Invoking SuperClass constructor

Suppose we have a parent class and a child class, whenever the compiler calls the child class constructor, it first calls its parent class constructor implicitly using the super() method and after which it calls the child class constructor.

If we see in the below example, we have ParentClass as College and ChildClass as Department. During execution, when the compiler creates a new object instance for the department class before it invokes the child constructor, it first implicitly invokes the college constructor using super keyword. This is why in the output we can notice that first, the college constructor statement is printed before the department constructor statement.

READ  Java While Loop

Parent Class file

public class College {
  
  public College() {
    System.out.println("College Name is BITS Pilani");
  }
}

Child Class file

public class Department extends College {

  public String dept;
  public Department(String deptname) {
    dept = deptname;
  }
  public static void main(String[] args) {
    Department d = new Department("Computer Science");
    System.out.println("Department Name:" + d.dept);
  }

}
College Name is BITS Pilani
Department Name:Computer Science

Copy Constructors

We can copy the value of one object to another using Java constructor. Apart from the constructor, we can also copy values using the clone() method of an Object class or by assigning values of one object to another.

Let’s see an example using the constructor in Java. The first constructor has an int and String as a parameter and the second has an object as a parameter. This is used as a copy constructor. If we notice the output, both objects display the same values which mean, we have copied the values of object e1 to object e2 using a constructor.

public class Employee {
  int empId;
  String empName;

  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  
   //Copy constructor
  public Employee(Employee emp) {
    empId = emp.empId;
    empName = emp.empName;
  }
  
  public void displayDetails() {
    System.out.println("Employee ID:" + empId);
    System.out.println("Employee Name:" + empName);
  }
  
  public static void main(String[] args) {
    Employee e1 = new Employee(102,"Dev");
    //Create a copy of another object
    Employee e2 = new Employee(e1);
    e1.displayDetails();
    e2.displayDetails();
  }

}

Employee ID:102
Employee Name:Dev
Employee ID:102
Employee Name:Dev

The below example shows you how you can copy the values without using constructors. Here we assign the values of one object to another.

public class Employee {
  int empId;
  String empName;
  
  public Employee(int id, String name) {
    this.empId = id;
    this.empName = name;
  }
  public Employee() {
    
  }
  
  public void displayDetails() {
    System.out.println("Employee ID:" + empId);
    System.out.println("Employee Name:" + empName);
  }
  public static void main(String[] args) {
    Employee e1 = new Employee(102,"Dev");
    Employee e2 = new Employee();
    e2.empId = e1.empId;
    e2.empName = e1.empName;
    e1.displayDetails();
    e2.displayDetails();
  }

}

Employee ID:102
Employee Name:Dev
Employee ID:102
Employee Name:Dev

In this article, we have already covered types of Java Constructors, Constructor Overloading, and Constructor Chaining. Now let’s discuss some differences between Method and Constructor.

Difference between Method and Constructor in Java

Even though many call a constructor as a special method, there are actually several differences between a Method and Constructor in Java.

Java ConstructorJava Method
Initializes a state of objectDescribes the behavior of the object
Does not have return typeIt has return type
It is invoked implicitlyIt is invoked explicitly
Constructor name should be same as class nameMethod name can be anything irrespective of class name

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions