What is Constructor in Java with Example Program?
In the current article about what is constructor in java with an example program, we are going to learn constructor definition, uses and other queries related to java constructor such as constructor uses, copy constructor, java constructor interview questions, and more. So Let’s start and keep learning./p>
Definition:
A constructor in Java is a java class method that is used to initialize objects attributes.
it is called a class constructor implicitly when an object is created using a Java new keyword.
Constructor with Example Program:
Employee emp = new Employee("John", 10001, "HR");
Here Object emp is created using a new keyword and its attributes initialized by invoking constructor as defined below.
Employee(String name, int employeeID, String department) {
this.name = name;
this.employeeID = employeeID;
this.department = department;
}
And set the attributes such as name, employeeId, department from passing parameter while creating object using new keyword.
Key points about constructor
- Name of Constructor must keep same as class name
- Constructor has no return type.
- Constructor is implicitly called when an instance is created using a new keyword.
- Compiler creates default constructor in case there is no existence of constructor code block defined in class.
Demonstration of what is constructor in java with example program as below
public class Employee {
private String name;
private int employeeID;
private String department;
public Employee(String name, int employeeID, String department) {
this.name = name;
this.employeeID = employeeID;
this.department = department;
}
public void showEmployeeInfo() {
System.out.println("Name : " + this.name);
System.out.println("EmployeeID : " + this.employeeID);
System.out.println("Department : " + this.department);
}
public static void main(String[] args) {
Employee emp = new Employee("John", 10001, "HR");
System.out.println("Display Employee details initialized via constructor.");
// Show Employee details initialized via constructor
emp.showEmployeeInfo();
}
Output:
Name : John
EmployeeID : 10001
Department : HR