Constructor

What is constructor?

Constructor is a block of code which use to initialize an object.

Constructor must have a same name of the class with no return type. Constructor gets automatically invokes when an object of that class is created.

There are three types of constructor in Java:

  • No-arg Constructor
  • Defalut Constructor
  • Parameterized Constructor

No-arg Constructor:

This is called as no argument (or no-arg) constructor as it doesn’t take any argument. If any java class doesn’t implement any constructor, Java compiler inserts a default constructor.

public class Employee{
int employeeId;

//Constructor
private Employee(){
System.out.println("Constructor Called");
employeeId = 1;
}

Public static void main(String[] args) {
Employee = emp = new Employee();
System.out.println("Employee ID : "+emp. employeeId);
}
}OUTPUT:Constructor CalledEmployee ID : 1

Default Constructor:

Java compiler will create default constructor if class doesn’t find any no-argument constructor. In below code the Java default compiler will initialize the employeeId and b to 0 and false respectively.

public class Employee{
int employeeId;
boolean b;
Public static void main(String[] args) {
Employee = emp = new Employee();
System.out.println("Employee ID : "+emp. employeeId);
System.out.println("b : "+emp.b);
}
}OUTPUT:Employee ID : 0b : false

Parameterized Constructor:

Constructor having an argument known as parameterized constructor.

public class Employee{
int employeeId;

//Parameterized Constructor
Employee( int empId){
System.out.println("Constructor Called");
employeeId = empId;
}
Public static void main(String[] args) {
Employee = emp = new Employee(5);
System.out.println("Employee ID : "+emp. employeeId);
}
}OUTPUT:Constructor CalledEmployee ID : 5

Notes:

  1. Constructors are invoked implicitly on object instantiation.
  2. Constructor will never have any return type.
  3. Name of the constructor will depend on the class name.
  4. Constructor can be overloaded but cannot be override.
  5. Constructor can never be static, abstract or final.

Difference between Java method and constructor?

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0