Day 12: Understanding Constructors in Java
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
Employeedeclares three instance variables:empId,empName, andempAge. - The parameterized constructor
Employeeaccepts three arguments and assigns them to the instance variables using thethiskeyword. - In
main, an objectkumaris created with the specified values.
System.out.println(kumar.empId);prints101.
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 objectempId→ constructor parameter
This ensures the passed value is stored in the object.