• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer
  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc
Tech Stack Journal

Tech Stack Journal

Constructor in Java: All You Need To Know

Contents

  • 1 Definition
  • 2 A Very Simple Example of a Constructor
  • 3 Default Constructor
  • 4 Constructor with Arguments
  • 5 Constructor Overloading
  • 6 Frequently Asked Questions on Constructor in Java
    • 6.1 Can constructor be private?
    • 6.2 What is the difference between class and constructor?
    • 6.3 Can constructor be final?
Photo by Ricardo Gomez Angel on Unsplash

Definition

A Constructor is a block of code which gets executed by Java when you create an instance of a class. Constructor looks similar to a function. But they do not have a return type. The name of a constructor must be a class name.

If I’m creating an Employee class, I can write the constructor as:

public Employee() {
	// Code
}

A Very Simple Example of a Constructor

package com.techstackjournal;

public class Employee {

	public Employee() {
		System.out.println("In Employee() Constructor...");
	}

	public static void main(String args[]) {
		Employee emp = new Employee();
	}

}

In this class, we just have a constructor. It is printing a simple message. I’m creating an instance of this class in the main method. That’s it, I’m not calling any method on that reference variable. The output of this program will be as below.

In Employee() Constructor...

How that message got printed without calling the constructor? We do not call the constructor. Java interpreter will call the constructor while instantiating the class. Since we are creating an object without passing arguments by writing new Employee(), Java will search if there is a constructor without arguments and executes it.

Default Constructor

In Java, every class will have a constructor. If you do not write a constructor, Java will insert one empty constructor for you. We call this empty constructor as a default constructor. A default constructor doesn’t contain any arguments or code. If you write at least one constructor, this automatic insertion of default constructor doesn’t happen.

Constructor with Arguments

Since constructor is the first thing that gets executed when we create an object, it is the best place to initialize the object.

Constructor can have arguments, but it is not a function, so it will not have a return statement.

package com.techstackjournal.app.types;

public class Employee {

	private String id;
	private String name;
	private double salary;

	public Employee(String id, String name, double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}

}

In this class, we’ve one Employee constructor which takes multiple variables as constructor arguments, which are being used for initializing the instance variables.

Here, id, name and salary are constructor arguments or just variables. However, this.id, this.name and this.salary are the instance variables.

Keyword this always refers to the current object.

Keyword this is not mandatory to refer the instance variables, however, when the argument variable and instance variable both have the same name, we can use this keyword to differentiate both of them. But it is a general practice to use this keyword when we are referring to the instance variable.

Let’s create a main program to create an instance of this Employee class using constructor.

package com.techstackjournal.app.main;

import com.techstackjournal.app.types.Employee;

public class Application {

	public static void main(String[] args) {

		Employee emp = new Employee("E001", "John Doe", 8000);

		System.out.println(emp);

	}

}

In this main program, we are passing the employee details while creating an instance of Employee class.

We need to make sure the order of the arguments is matching with the definition of the constructor. Since Employee constructor accepts first two arguments as String and the last argument as double, we need to pass the arguments in similar sequence. However, if you pass name first and employee id next, Java cannot warn you anything as for it both of them are Strings.

When there were no constructors in the class, we could create an instance of the class using an empty constructor. But if a class contains at least one constructor with arguments but not an empty constructor, you will not be able to instantiate the class using empty constructor call now.

Employee emp = new Employee();

Above line of code will throw a compilation error as we do not have empty constructor in the class.

Constructor Overloading

Writing more than one constructor in a class with unique set of arguments is called as Constructor overloading. When you have more than one constructor,

package com.techstackjournal.app.types;

public class Employee {

	private String id;
	private String name;
	private double salary;

	public Employee() {
		System.out.println("Constructing with 1 argument...");
		this.salary = 8000;
	}

	public Employee(String id, String name) {
		System.out.println("Constructing with 2 arguments...");
		this.id = id;
		this.name = name;
	}

	public Employee(String id, String name, double salary) {
		System.out.println("Constructing with 3 arguments...");
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}

}

In the above class, there are 3 constructors, a constructor without arguments, a constructor with 2 arguments and a constructor with 3 arguments.

Let’s create a main program to consume this Employee class.

package com.techstackjournal.app.main;

import com.techstackjournal.app.types.Employee;

public class Application {

	public static void main(String[] args) {

		Employee emp1 = new Employee();
		Employee emp2 = new Employee("E001", "John Doe");
		Employee emp3 = new Employee("E002", "John Doe", 9000);

		System.out.println("Employee 1: " + emp1);
		System.out.println("Employee 2: " + emp2);
		System.out.println("Employee 3: " + emp3);

	}

}
Constructing with 1 argument...
Constructing with 2 arguments...
Constructing with 3 arguments...
Employee 1: Employee [id=null, name=null, salary=8000.0]
Employee 2: Employee [id=E001, name=John Doe, salary=0.0]
Employee 3: Employee [id=E002, name=John Doe, salary=9000.0]

As you can see in the output, creating an object without any arguments will call no-arg constructor, creating an object with 2 arguments calls 2-arg constructor and so on.

Frequently Asked Questions on Constructor in Java

Can constructor be private?

Yes, if you do not want anyone to create an instance of a class, you can declare a constructor as private. To use a class with private constructor, you need to expose its methods by declaring them as static.

What is the difference between class and constructor?

A class is a template, and it contains member variables, member functions, class methods and constructors too. However, a constructor which also has the same name as that of its class is just a piece of code within the class itself. When we instantiate a class, Java automatically calls respective constructor.

Can constructor be final?

No, we can only declare a class, method and variable as final. Declaring a constructor as final doesn’t make sense, as a sub-class anyway doesn’t inherit constructors from its parent. Each class has its own constructors.

Primary Sidebar

More to See

Arrays.asList in Java Examples

February 21, 2021 By Admin

[Solved] Why List.add throws UnsupportedOperationException in Java?

February 20, 2021 By Admin

Secondary Sidebar

  • Java Tutorial
    • Introduction
    • Install Java
    • First Java Program
    • Statements and Comments
    • Packaging the Classes
    • Variables
    • Primitive Data Types
    • Operators
    • if-else statement
    • Loops in Java
    • Arrays
    • break and continue
    • Switch Statement
    • Classes and Objects
    • Methods
    • Encapsulation
    • Constructor in Java: All You Need To Know
    • Inheritance
    • Access Modifiers
    • Static Variables and Methods
    • Final keyword in Java
    • Abstract Class
    • What is an Interface in Java?
    • Method Overloading
    • Java – Method Overriding
    • Polymorphism
    • Java – super Keyword
    • Nested Classes
    • Exception Handling
    • String Class

Categories

  • Algorithms
  • Blogging
  • Docker
  • Java
  • Misc
  • Node.js
  • Spring Core
  • Windows

Archives

  • February 2021 (6)
  • January 2021 (1)
  • December 2020 (1)
  • September 2020 (2)
  • August 2020 (5)
  • July 2020 (4)
  • June 2020 (1)
  • May 2020 (4)
  • April 2020 (22)
  • November 2019 (3)
  • September 2019 (2)
  • August 2019 (6)

Footer

Navigation

  • Home
  • Java Tutorial
  • Java Posts
  • Node.js
  • Spring Core
  • Algorithms
  • Docker
  • Blogging
  • Misc

Recent

  • How to Make File Explorer Open to This PC instead of Quick Access in Windows 10
  • Arrays.asList in Java Examples
  • [Solved] Why List.add throws UnsupportedOperationException in Java?
  • How to Convert an Array to List in Java?
  • How Many Spaces in a Tab?

Search

Copyright © 2021 · Tech Stack Journal · Log in