Java Constructor, Method and Variable comprises of basic constructs in coding. The importance of Java Constructor is it gives properties to an object at the time of creation itself; else requires many method calls.
Before going into coding, let us know what a Java constructor is. A Java constructor looks like a method but without return type. Moreover, constructor is called implicitly when an object is created.
Let us see one Example on Java Constructor giving properties to an object.
public class Employee
public Employee() // default constructor
public Employee(String name, int service, double salary) // overloaded constructor
this.name = name;
this.service = service;
this.salary = salary;
System.out.println("Variables are assigned");
public static void main(String args)
Employee emp1 = new Employee("Srinivas", 5, 9832.55);
System.out.println(emp1.name + " service is " + emp1.service + " years with Salary of Rs." + emp1.salary);
In the above class Employee, there are two constructors – one default and one overloaded. A constructor without parameters is known as default constructor and with parameters is known as overloaded constructor. Here, the default constructor just does the job of printing a message. Infact, two access two constructors, two objects should be created. But with one object also other constructor can be accessed. The magic is this(). this() calls the default constructor. The instance variables are assigned in the constructor and used in the main(). If variables are not assigned in constructor, it requires many method definitions and calls.
Following links of this Web site gives indepth study of constructors.
1. Java Constructors: Learn through Questions and Answers
2. Constructor – General Discussion – Overloading
3. What a constructor returns?