What is Constructor ?


Each object we created must be initialized to some value. We can do this in two ways -

1 - We can initialize objects by using dot operator -

emp1.id = 1;
emp1.name="Tom";
2 - Secondly we can initialize objects by using methods -
emp1.setId(1);
emp1.setName("Tom");
But the initialization of objects is so common that Java enables objects to initialize themselves when they are created.

This automatic initialization is done through the use of Constructor.

Constructors are similar to methods and have the following features -
1- They have the same name as class name.
2- They do not have any return type, not even void.
3- They run automatically as a new object is created and run only once for any object.
4- If we do not explicitly create any constructor in class than a default constructor is automatically created by Java run time system.

Example 1-


class Employee
 {
  public void a()
  {
   System.out.println("AAA");
  }
  public void b()
  {
   System.out.println("BBB");
  }
  public Employee()     // Constructor
  {
   System.out.println("You are in Constructor");
  }   
 }

 public class Demo
 {
  public static void main(String args[]) 
  {
   Employee emp1 = new Employee();     // Calling constructor
   
   //emp1.Employee();    Error we cannot call constructors like simple methods.
   
   emp1.a();
   emp1.b();
  }
 }

       

Output -

You are in Constructor
AAA
BBB

Program Description -

Note that constructor :
public Employee() 
{
 System.out.println("Constructor");
}   
Have the same name as class name and also do not have any return type.

As we create the object by writing the code: Employee emp1 = new Employee(); compiler will search for a Employee() constructor in Employee class and run it automatically. That is why 'You are in Constructor' is printed first .

Also note that constructor runs only once for any object when we create that object, we cannot call them multiple times like java methods.

Types of Java Constructor -

Constructor is of two types -

1- Constructor without parameter (Default Constructor) - If a constructor does not have any parameter than it is called Default Constructor, as constructor created in last example.

If you do not define any constructor explicitly, a default constructor is automatically built by java run time system.

For example -
class Employee
{
}
Even though we have not define anything within the class but compiler will automatically generate a default constructor within the class like this -
public Employee() 
{
}   
Note - A default constructor initializes all data members (variables) of the class to their default values.

2 - Constructor with parameter (Parameterized Constructor) - If a constructor has one or more parameters then it is called parameterized constructor.

For example -
public Employee(int i, String n)
{
 //Statements;
}
Example -

class Employee
{
 int id;
 String name;
 public void input()
 {
  id = Integer.parseInt(System.console().readLine("Enter ID"));
  name  = System.console().readLine("Enter name");
 }
public void disp()
{
 System.out.println(id+ "  " + name);
}
  
public Employee(int i, String n)      // parameterized constructor
{
 id = i;
 name = n;
}
}

public class Demo
{
 public static void main(String args[]) 
 {
  Employee emp1 = new Employee(1, "Tom");
  emp1.disp();
 }
}    

    
Output-
1  Tom
       
Note that when the code Employee emp1 = new Employee(1, "Tom"); will execute, compiler will look for a constructor in Employee class that contain two parameters, where first parameters is of int type and second is of string type, when it finds a match that matching constructor will executes. So here it will find a match with the only constructor we have, and execute it. It causes id and name of emp1 to be set at the value i (i.e. 1 in this case) and n (i.e. 'Tom in this case').


Always remember that if we define any constructor explicitly then default constructor does not built by compiler. So in the above example there will be no default constructor built by complier. So if we try to execute the following code

Employee emp1 = new Employee();

There will be error. Because now compiler will look for a constructor in Employee class that does not have any parameter but it will not find any such constructor. So there will be error.

Constructor Overloading -

If we define more than one constructor within a class then it is called constructor overloading.
A class can have any number of constructor as long as their parameter declaration is different i.e. either the number of parameter or data type of parameter should be different.

Example -


class Employee
{
 int id;
 String name;
 public void input()
 {
  id = Integer.parseInt(System.console().readLine("Enter ID"));
  name  = System.console().readLine("Enter name");
 }
 public void disp()
 {
  System.out.println(id+ "  " + name);
 }
  
 public Employee()     // Constructor 1
 {
 }
  
 public Employee(int i)    // Constructor 2
 {
  id = i;
 }
 public Employee(String n)     // Constructor 3
 {
  name = n;
 }
 public Employee(int i, String n)    // Constructor 4
 {
  id = i;
  name = n;
 }
 public Employee(String n, int i)    // Constructor 5
 {
  id = i;
  name = n;
 }
}

public class Demo
{
 public static void main(String args[]) 
  {
   Employee emp1 = new Employee();
   Employee emp2 = new Employee(1);
   Employee emp3 = new Employee("Tom");
   Employee emp4 = new Employee(1, "Tom");
   emp1.disp();
   emp2.disp();
   emp3.disp();
   emp4.disp();   
  }
}
       

       

Output -

0  null
1  null
0  Tom
1  Tom
Here we have defined 5 constructors, Constructor 1 does not have any parameter, Constructor 2 has 1 parameter of int type, Constructor 3 also has 1 parameter but it is of String type, and so on.

When the code Employee emp1 = new Employee(); gets executed, it will cause the compiler to look for a constructor that is not having any parameter, so Constructor 1 will gets executed and initialize data fields of emp1 to their default value (i.e. 0 for int and null for String)



Note the default value of object type is null.

The next line Employee emp2 = new Employee(1); will cause the compiler to look for a constructor that is having only one parameter of int type , so Constructor 2 will gets executed and initialize id to 1 and name to null.



The next line Employee emp3 = new Employee("Tom"); will cause the compiler to look for a constructor that is having only one parameter of String type , so Constructor 3 will gets executed and initialize id to 0 (default value of int) and name to "Tom".



The next line Employee emp4 = new Employee(1,"Tom"); will cause the compiler to look for a constructor that is two parameters 1st is of int type and 2nd is of String type , so Constructor 4 will gets executed and initialize id to 1 and name to "Tom".



Copy Constructor -

This constructor is used to create a copy of object.

Example -


class Employee
{
 int id;
 String name;

 public void input()
 {
  id = Integer.parseInt(System.console().readLine("Enter ID"));
  name  = System.console().readLine("Enter name");
 }
 public void disp()
 {
  System.out.println(id+ "  " + name);
 }
  
public Employee(int i, String n)    
{
 id = i;
 name = n;
}
public Employee(Employee emp)    // Copy Constructor
{
 id = emp.id;
 name = emp.name;
}
}

        
public class Demo
{
 public static void main(String args[]) 
 {
   Employee emp1 = new Employee(1, "Tom");
   emp1.disp();
   Employee emp2 = new Employee(emp1);
   emp2.disp();
  }
}
      

      

Output -

1   Tom
1   Tom
When the code Employee emp1 = new Employee(1, "Tom"); gets executed, it will call the constructor and set emp1 id to 1 and name to 'Tom'.

Next line emp.disp(); will call disp() method to display id and name of emp1 object.



the next line Employee emp2 = new Employee(emp1); will call the second constructor and the value of emp in constructor will be equal to emp1 i.e. emp now will refer to same object as emp1.



When constructor gets executed it will set emp2 id and name to emp.id (i.e. 1) and emp.name (i.e. Tom). So created exact copy emp1. That is why it is called Copy Constructor.



The next line will display the id and name of emp2.

Chaining Of Constructors -

We can also chain constructor to each other using this(). While chaining you should remember the following rules -
1- One constructor can chain only one constructor.
2- this() should be the first statement within constructor.
3- It should not form a cycle while chaining. i.e. -

Example -


class Employee
{
 int id;
 String name;
         
 public void input()
 {
  id = Integer.parseInt(System.console().readLine("Enter ID"));
  name  = System.console().readLine("Enter name");
 }
 public void disp()
 {
  System.out.println(id+ "  " + name);
 }
  
 public Employee(int i)      // Constructor 1
 {
  id = i;
 }
 public Employee(String n)    // Constructor 2
 {
  name = n;
 }
  
 public Employee(int i, String n)   // Constructor 3 
 {
  this(i);       // chaining to constructor 1
  name = n;
 }
  
 public Employee(String n, int i)    // Constructor 4
 {
  this(i,n);    // chaining to constructor 3
 }
 public Employee(Employee emp)    // Constructor 5
 {
  this(emp.name);   // chaining to constructor 2
  id = emp.id;
 }
}

public class Demo
{
 public static void main(String args[]) 
 {
  Employee emp1 = new Employee("John", 2);
  emp1.disp();
 }
}
       

       
When the code Employee emp1 = new Employee("John", 2); gets executed , It will call to constructor 4 and the statement this(i,n) will call to a constructor that have first parameter of int type and second parameter of String type, So it will call to constructor 3.
Constructor 3 contain the 1st statement this(i) , it will call to a constructor that contain only 1 parameter of int type so constructor 1 will be executed and set the id of emp1 to 1.
Then it will come back to constructor 3 that will set the name of emp1 to 'John' and finally it come back to constructor 4.
The next line emp1.disp(); will display id and name of emp1.

'this' keyword -

this means 'object of current class'. It refers to the current object.
'this' keyword is normally used to differentiate between local and class variables within a method. When local variables within method have the same name as class variables then local variables hides the class variables. In that case this keyword is used to refer class variables.
For example - consider the Constructor 4 of previous example -
public Employee(int id, String name)
{
 this.id = id;
 this.name = name;
}
Here this.id refers to object's id and id refers to method's id. Similarly this.name refers to object name and name refers to method name.

Method Overloading (Function Overloading) -

In java it is possible to have multiple methods with the same name in a class as long as their parameter declarations are different i.e. either the number of parameters or data types of parameters are different. In this case methods are said to be overloaded and process is referred as method overloading. This is one of the ways Java supports the concept of Polymorphism.
When an overloaded method is called, Compiler checks for the number and data types of parameters to determine which overloaded method to call.
Note - Always remember that there is no method overloading on the basis of return type of methods.

Example -


class Test
{
 public int sum(int a)    // version 1
 {
   return (a+a);
 }
public int sum(int a, int b)   // version 2
{
 return (a+b);
}
public double sum(double a)   // version 3
{
 return (a+a);
}
public double sum(double a, double b)  // version 4
{
 return (a+b);
}
}

public class Demo
{
  public static void main(String[] args) 
  {
   Test t1 = new Test();
   int sum1 =  t1.sum(1);    // call to version1
   int sum2 =  t1.sum(1,2);  // call to version2
   double sum3 = t1.sum(10.5);   // call to version3
   double sum4 = t1.sum(11.5, 12.5);     // call to version4
   System.out.println(sum1+"  "+sum2+"  "+sum3+"  "+sum4);
   }
}

         
       

Output -

2  3  21.0  24.0
       
Here we have overloaded a method named sum four times. The first version contains an int parameter, second version contains two parameters of int type, third version contains single double parameter and fourth version contains two double type parameters.
The return type of overloaded method can be same or different, because there is no overloading on the basis of return type.
When the code int sum1 = t1.sum(1); gets executed, compiler looks for the version of sum method, that contain one parameter of int type so version 1 will gets executed and return the result in sum1 variable.
Similarly when int sum2 = t1.sum(1,2); gets executed, compiler looks for that version of sum method that contain two parameters of int type so second version will gets executed and return the result in sum2 variable and so on.
It is clear from the above example when an object call to an overloaded method, compiler looks for a match between the values used to call the method and method parameters.
But there can be case when compiler does not find exact match. In that case java automatically performs type conversion to call the method and this conversion is only possible if method parameter data type is larger in size compared to arguments (values) used to call the method. This conversion is only take place when compiler does not find exact match.

For Example -


class Test
{
 public int sum(int a, int b)   // version 1
 {
  return (a+b);
 }
 public double sum(double a)   // version 2
 {
  return (a+a);
 }   
}

public class Demo
{
 public static void main(String[] args) 
 {
  Test t1 = new Test();
  int sum1 =  t1.sum(1, 2);     // call to version1
  double sum2 =  t1.sum(10);    // call to version2
  double sum3 = t1.sum(10.5);   // call to version2
  System.out.println(sum1+"  "+sum2+"  "+sum3);
 }
}

Here when the code double sum2 = t1.sum(10); gets executed compiler will look for the version of sum that contain one parameter of int type, but there is no such sum method, So automatic type conversion take place and int value gets converted into double and version2 of sum gets call and return the result in sum2 variable.