Java Constructor

Java 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:

  • 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 class doesn’t implement any constructor, 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 method and constructor?

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan