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:
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
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
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
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.
📝 Blogs
javadoubts.com © All rights reserved