Day 12: Understanding Constructors in Java

Published: (January 8, 2026 at 10:35 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

What is a Constructor?

A constructor is a special method in Java that is automatically called when an object is created.

  • The constructor name must be the same as the class name.
  • It does not have a return type.
  • It is called automatically when an object is created.
  • Used to initialize instance variables.

Why Do We Need Constructors?

Constructors help to:

  • Initialize object values.
  • Reduce extra setter methods.
  • Ensure objects are created in a valid state.
  • Improve code readability and structure.
class Student {
    Student() {
        System.out.println("Constructor called");
    }
}

When an object of Student is created, the constructor executes automatically.

Java mainly has two types of constructors:

Default Constructor

A default constructor is a constructor with no parameters.

class Employee {
    Employee() {
        System.out.println("Hi");
    }

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

When the object emp is created, the default constructor is called and prints Hi.

Parameterized Constructor

A parameterized constructor accepts parameters to initialize object variables.

class Employee {
    int empId;
    String empName;
    int empAge;

    Employee(int empId, int empAge, String empName) {
        this.empId = empId;
        this.empAge = empAge;
        this.empName = empName;
    }

    public static void main(String[] args) {
        Employee kumar = new Employee(101, 20, "Kumar");
        System.out.println(kumar.empId);
    }
}

In this example:

  • The class Employee declares three instance variables: empId, empName, and empAge.
  • The parameterized constructor Employee accepts three arguments and assigns them to the instance variables using the this keyword.
  • In main, an object kumar is created with the specified values.
    System.out.println(kumar.empId); prints 101.

A parameterized constructor allows us to initialize object values at the time of object creation using arguments.

this Keyword in Constructors

What is this?

this is a reference variable that refers to the current object.

this Keyword

When constructor parameters and instance variables have the same names, Java gives priority to the parameters. The this keyword is used to differentiate instance variables from parameters:

this.empId = empId;
  • this.empId → instance variable of the current object
  • empId → constructor parameter

This ensures the passed value is stored in the object.

Back to Blog

Related posts

Read more »