Constructor in java

Let’s learn constructor in java.

Constructor in java

Constructor is a special method or block of code used to initialize parameters or initial values of the fields.

constructor in java

This special method will be invoked at the time of creation of an object. It will be automatically called when you create an object.

How to define special method called Constructors?

Here’s the syntax,

class DemoClass
{
   // constructor name is same as class name
   DemoClass()
   {
      ....
   }
}

// calls DemoClass() constructor
DemoClass obj = new DemoClass();

In the above code when we type new DemoClass with brackets and with no parameters, that’s when actually constructor is executed automatically.

So constructor is only called once at the start when we are creating the object. Basically the purpose of the constructor is for to essentially initialize the object.


NOTE:

  • Constructor does not have any return type.
  • Constructor name is same as class name.
  • Constructor is called when an object of a classs is created.
  • Access modifiers applicable for constructors are public, private, protected and default.
  • Constructor gets called when we write “new()” keyword.

Types of constructor

  • No arg constructor
  • Parameterised constructor

No-argument (no arg constructor)

No-argument (no-arg constructor) is a constructor with no arguments. If a class do not have constructor then compiler creates default constructor with no arguments. Let’s see an example on no-arg constructor.

class NoArgExample
{ 
   int number; 
   String name; 
   NoArgExample() 
   { 
      System.out.println("Constructor called"); 
   } 
}
public class NoArgConstructorDemo 
{
   public static void main(String[] args) 
   {
      // this will invoke default constructor. 
      NoArgExample obj = new NoArgExample();
      // default constructor provides default 
      // values to object like 0, null 
      System.out.println(obj.name); 
      System.out.println(obj.number);
   }
}

Output:

Constructor called
null
0


NOTE: if there is no constructor in a class then compiler automatically creates default constructor. Here’s how it looks in .class file,

// Employee.java
class Employee
{
   public static void main(String args[])
   {
      // invoking default constructor
      Employee emp = new Employee();
   }
}

// Employee.class
class Employee
{
   Employee()
   {

   }
   public static void main(String args[])
   {
      Employee emp = new Employee();
   }
}

Parameterized constructor

Parameterized constructor is a constructor which has fixed number of parameters.

Parameterized constructor main purpose is to provide different values to objects. Let’s see an example on parameterized constructor.

class Employee
{
   int empID;
   String empName;
   // parameterized constructor
   Employee(int ID, String name)
   {
      empID = ID;
      empName = name;
   }
   void print()
   {
      System.out.println(empID + " " + empName);
   }
   public static void main(String args[])
   {
      Employee obj1 = new Employee(232, "dhoni");
      Employee obj2 = new Employee(233, "virat");
      obj1.print();
      obj2.print();
   }
}

Output:

232 dhoni
233 virat


Constructor overloading in java

Constructor overloading is an approach of having more than one constructors in a class with different arguments performing different tasks.

Constructors can be overloaded like methods. Let’s see constructor overloading program in java.

class Employee
{
   int empID;  
   String empName;  
   int empAge;  
   // two argument constructor  
   public Employee(int id, String name)
   {  
      empID = id;  
      empName = name;  
   }  
   // three argument constructor  
   public Employee(int id, String name, int age)
   {  
      empID = id;  
      empName = name;  
      empAge = age;  
   }  
   void print()
   {
      System.out.println(empID + " " + empName + " " + empAge);
   }
   public static void main(String args[])
   {  
      Employee obj1 = new Employee(232, "dhoni");  
      Employee obj2 = new Employee(233, "virat", 26);  
      obj1.print();
      obj2.print();
   }
}

Output:

232 dhoni 0
233 virat 26


Constructor chaining in java

class Rectangle
{
   private int a;
   private int b;
   private int height;
   private int width;

   // first constructor
   public Rectangle()
   {
      this(0, 0); // calls second constructor
   }
   // second constructor
   public Rectangle(int height, int width)
   {
      this(0, 0, height, width); // calls third constructor
   }
   // third constructor
   public Rectangle(int a, int b, int height, int width)
   {
      this.a = a;
      this.b = b;
      this.height = height;
      this.width = width;
   }
}

In the above example we have three constructors. First constructor calls second, the second constructor calls the third constructor and the third constructor initializes the instance variables.

Here third constructor does all the initialization. Regardless what constructor we call, the variables will always be initialized in third constructor. This is known as constructor chaining.

So the last constructor has the responsibility to initialize the variables. Constructor chaining helps avoid code duplication.


When we can use constructor in java?

Constructor or special method can be used to execute some set of code which has to be executed at the time of object creation.