Java Constructors
A Constructor in Java is a special method which is used to initialize object. The constructor is called when the object is created. It can be used to initialize object attributes. The constructor name should be same as the class name and it cannot have a return type (like void).
Example
public class ConstructorExample { int x; public ConstructorExample () { x = 100; } public static void main(String args[]){ ConstructorExample myObj = new ConstructorExample(); System.out.println(myObj.x); } }
Output
100
Note:
Constructor Parameters
Constructors can also take parameters, which is used to initialize parameters.
Example
In the below example, we create a class attribute ‘x’ and inside the constructor we set the value of x which is x=y. While creating the object myObj, we pass the value 50 which is assigned to x in the Constructor.
public class ConstructorExample { int x; public ConstructorExample (int y) { x = y; } public static void main(String args[]){ ConstructorExample myObj = new ConstructorExample(50); System.out.println(myObj.x); } }
Output
50
The constructor can also have as many parameters.
Example
In the below example, we pass two parameters to the class constructor Employee:
public class Employee { String emp_name; int emp_salary; public Employee (String name, int salary){ emp_name = name; emp_salary = salary; } public static void main (String args[]){ Employee emp = new Employee("Johnson", 12000); System.out.println("Employee name : "+emp.emp_name); System.out.println("Employee salary : "+emp.emp_salary); } }
Output
Employee name : Johnson Employee salary : 12000