Constructor in java

Let’s learn constructor in java.

constructor in java

Constructor in java

Constructor is a special method or block of code used to initialize object and called when an instance is created. Constructor is similar to method.

NOTE:

  • constructor never return value or return type.
  • constructor name is same as class name.
  • static, abstract, final keywords can’t be used for constructors.
  • constructors can be public or private or protected or default.

Constructor is called when we write “new()” keyword. At this point memory is allocated in memory for object.

Syntax:

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

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

Example:

class ConstructorDemo
{
   int salary;
   ConstructorDemo()
   {
      this.salary = 60000;
   }

   public static void main(String[] args)
   {
      ConstructorDemo obj = new ConstructorDemo();
      System.out.println(obj.salary);
   }
}


Output:

60000

why we use constructor in java?

The purpose of constructor is,

  • constructor is used to allocate memory to the object.
  • constructor is used to initialize values.
  • java compiler creates a default constructor when there is no constructor in a class.
  • constructor is the first method which will be executed.

Types of constructor

  • Default constructor/non parameterized constructor
  • No-argument constructor
  • Parameterised constructor

Default constructor in java/non parameterized constructor

Java compiler adds default constructor/non parameterized constructor with no arguments with empty definition if a class does not have or there is no constructor.

Default constructor or non parameterized constructor’s main purpose is to provide default values to an object depending on data type. Let’s see an example,

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

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



Now let’s see an example on default constructor that prints or displays default values.

public class DefaultConstructorDemo 
{
   int empID;  
   String empName;  
   void print()
   {
      System.out.println(empID + " " + empName);
   }
   public static void main(String[] args) 
   {
      // here we are creating objects  
      DefaultConstructorDemo obj1 = new DefaultConstructorDemo();  
      DefaultConstructorDemo obj2 = new DefaultConstructorDemo();  
      // print values of object  
      obj1.print();  
      obj2.print();
   }
}



Output:

0 null
0 null

No-argument (no-arg constructor) constructor

No-argument (no-arg constructor) constructor is a constructor with no arguments or parameter.

If a class has constructor with arguments then compiler does not create default constructor.

class Employee 
{
   String name;
   public Employee()
   {
      name = "Virat";
   }
}

public class NoArgConstructorDemo 
{
   public static void main(String[] args) 
   {
      Employee obj = new Employee();
      System.out.println("Employee name: " + obj.name);
   }
}



Output:

Employee name: Virat


Parameterized constructor

Parameterized constructor is a constructor with specified number of parameters.

Parameters can be of any type, that is, integer, character, array or an object. Let’s see a java program on parameterized constructor,

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



Output:

232 virat
233 dhoni


Constructor overloading with examples

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

Also read – this keyword in java

Constructors can be overloaded like methods. Let’s see a java program to overload constructors,

class Employee
{
   int empID;  
   String empName;  
   int empAge;  
   // two argument constructor  
   Employee(int id, String name)
   {  
      empID = id;  
      empName = name;  
   }  
   // three argument constructor  
   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 with examples

Constructor chaining means when a constructor calls another constructor of same class.

Constructor chaining initialization is done at single place.

NOTE:

  • one constructor calls another constructor using “this” keyword.
  • this keyword should be the first statement in constructor chaining else Unresolved compilation problem: Constructor call must be the first statement in a constructor.
class StudentDetails 
{
   public String studentName;
   public int studentID;
   public String studentDetails;
   
   // default constructor
   public StudentDetails()
   {
      // calling the constructor with String parameter
      this("Virat");
   }

   public StudentDetails(String name)
   {
      // calling constructor with (String, integer) parameter
      this(name, 1648);
   }

   public StudentDetails(String name, int ID)
   {
      // calling constructor with (String, integer, String) parameter
      this(name, ID, "Delhi");
   }

   public StudentDetails(String name, int ID, String detail)
   {
      this.studentName = name;
      this.studentID = ID;
      this.studentDetails = detail;
   }

   void printDetails() 
   {
      System.out.println("Student name : " + studentName);
      System.out.println("Student ID : " + studentID);
      System.out.println("Student details : " + studentDetails);
   }

   public static void main(String[] args) 
   {
      StudentDetails obj = new StudentDetails();
      obj.printDetails();
   }
}



Output:

Student name : Virat
Student ID : 1648
Student details : Delhi


Copy constructor in java

Java copy constructor is special type of constructor used to construct an object by copying the state from another object of same class.

Copy constructor takes argument of same class and provides copy of specified object.

NOTE: java does not provide copy constructor by default.

class JavaCopyConstructor
{
   int empID;
   String empName;
   
   JavaCopyConstructor(int id, String name)
   {
      empID = id;
      empName = name;
   }

   // java copy constructor
   JavaCopyConstructor(JavaCopyConstructor cc)
   {
      empID = cc.empID;
      empName = cc.empName;
   }

   void print()
   {
      System.out.println(empID + " " + empName);
   }

   public static void main(String[] args) 
   {
      // calling sample constructor
      JavaCopyConstructor obj1 = new JavaCopyConstructor(235, "Virat");
      // calling copy constructor by passing object of sample constructor
      JavaCopyConstructor obj2 = new JavaCopyConstructor(obj1);
      obj1.print();
      obj2.print();
   }
}



Output:

235 Virat
235 Virat