JAVA Constructor


A constructor is special method (Please note that it is not a method) inside the class which is called while instantiating of the object of that class. A constructor is invoked to create an object from the blueprint of the class.
A constructor is different from instance method only in two ways
  1.   It has the same name as the name of the class.
  2.  It has no return type

Below is the general declaration of the constructor as shown below


public class MyClass{

   //This is the constructor

   MyClass(){

   }

   ..

}

In above code snippet MyClass() { } is a constructor which defined just like an instance method but with two differents. i.e. It has the same name just like the name of the class and has no return type.

A simple constructor program in java showing the working of the constructor.

Here we have created an object obj of class Hello and then we displayed the instance variable nameof the object. As you can see that the output is BeginnersBook.com which is what we have passed to the name during initialization in constructor. This shows that when we created the object obj the constructor got invoked. In this example we have used this keyword, which refers to the current object, object obj in this example. We will cover this keyword in detail in the next tutorial.
public class Hello {
   String name;
   //Constructor
   Hello(){
      this.name = "Just a constructor call";
   }
   public static void main(String[] args) {
      Hello obj = new Hello();
      System.out.println(obj.name);
   }
}

Output:
Just a contructor call

Kindly of constructor

There are three kinds of constructors
1.  Default Constructor
2.  No Argument Constructor
3.  Parameterized Constructors

1.  Default Constructor

When no constructor is defined inside a class, JAVA code inserts a default constructor. This constructor is called a default constructor. Default constructor has no arguments and have nothing in its body. Default constructor does not exists physically inside the class but created automatically by the JAVA compiler while compilation of the program.

Below is the example of a default constructor. The public class Horse has no constructor as described below


Public class Horse {
Public static void main(Strings args[]){
Horse myhorse=new Horse();  
}
}
When above class is compiled, compiler inserts an automatically a default constructor. And program will looks like .

Public class Horse {

Horse()
{
}
Public static void main(Strings args[]){
Horse myhorse=new Horse();  
}
}
Horse() { } is default constructor which is inserted at compile time by the JAVA compiler.

no-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.
Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it.

Example: no-arg constructor

class Demo
{
     public Demo()
     {
         System.out.println("This is a no argument constructor");
     }
     public static void main(String args[]) {
           new Demo();
     }
}
Output:
This is a no argument constructor

Parameterized constructor

Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

Example: parameterized constructor

In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2.
public class Employee {
 
   int empId;  
   String empName;  
              
   //parameterized constructor with two parameters
   Employee(int id, String name){  
       this.empId = id;  
       this.empName = name;  
   }  
   void info(){
        System.out.println("Id: "+empId+" Name: "+empName);
   }  
             
   public static void main(String args[]){  
          Employee obj1 = new Employee(10245,"Chaitanya");  
          Employee obj2 = new Employee(92232,"Negan");  
          obj1.info();  
          obj2.info();  
   }  
}
Output:
Id: 10245 Name: Chaitanya
Id: 92232 Name: Negan

Example2: parameterized constructor

In this example, we have two constructors, a default constructor and a parameterized constructor. When we do not pass any parameter while creating the object using new keyword then default constructor is invoked, however when you pass a parameter then parameterized constructor that matches with the passed parameters list gets invoked.
class Example2
{
      private int var;
      //default constructor
      public Example2()
      {
             this.var = 10;
      }
      //parameterized constructor
      public Example2(int num)
      {
             this.var = num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example2 obj = new Example2();
              Example2 obj2 = new Example2(100);
              System.out.println("var is: "+obj.getValue());
              System.out.println("var is: "+obj2.getValue());
      }
}
Output:
var is: 10
var is: 100

What if you implement only parameterized constructor in class

class Example3
{
      private int var;
      public Example3(int num)
      {
             var=num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example3 myobj = new Example3();
              System.out.println("value of var is: "+myobj.getValue());
      }
}
Output: It will throw a compilation error. The reason is, the statement Example3 myobj = new Example3() is invoking a default constructor which we don’t have in our program. when you don’t implement any constructor in your class, compiler inserts the default constructor into your code, however when you implement any constructor (in above example I have implemented parameterized constructor with int parameter), then you don’t receive the default constructor by compiler into your code.
If we remove the parameterized constructor from the above code then the program would run fine, because then compiler would insert the default constructor into your code.

Constructor Chaining

When A constructor calls another constructor of same class then this is called constructor chaining.

Super()

Whenever a child class constructor gets invoked it implicitly invokes the constructor of parent class. You can also say that the compiler inserts a super(); statement at the beginning of child class constructor.
class MyParentClass {
   MyParentClass(){
          System.out.println("MyParentClass Constructor");
   }
}
class MyChildClass extends MyParentClass{
   MyChildClass() {
          System.out.println("MyChildClass Constructor");
   }
   public static void main(String args[]) {
          new MyChildClass();
   }
}
Output:
MyParentClass Constructor
MyChildClass Constructor

 

Constructor Overloading

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task.



Java Copy Constructor

A copy constructor is used for copying the values of one object to another object.
class JavaExample{  
   String web; 
   JavaExample(String w){  
          web = w;
   }  
 
   /* This is the Copy Constructor, it 
    * copies the values of one object
    * to the another object (the object
    * that invokes this constructor)
    */
   JavaExample(JavaExample je){  
          web = je.web; 
   }  
   void disp(){
          System.out.println("Website: "+web);
   }  
 
   public static void main(String args[]){  
          JavaExample obj1 = new JavaExample("JAVA TUTORIAL");  
                    
          /* Passing the object as an argument to the constructor
           * This will invoke the copy constructor
           */
          JavaExample obj2 = new JavaExample(obj1);  
          obj1.disp();  
          obj2.disp();  
   }  
}
Output:
Website: JAVA TUTORIAL
Website: JAVA TUTORIAL

 

Quick Recap

1.  Every class has a constructor whether it’s a normal class or a abstract class.
2.  Constructors are not methods and they don’t have any return type.
3.  Constructor name should match with class name .
4.  Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.
5.  Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.
6.  If you don’t implement any constructor within the class, compiler will do it for.
7.  this() and super() should be the first statement in the constructor code. If you don’t mention them, compiler does it for you accordingly.
8.  Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.
9.  Constructors can not be inherited.
10. If Super class doesn’t have a no-arg(default) constructor then compiler would not insert a default constructor in child class as it does in normal scenario.
11. Interfaces do not have constructors
12. Abstract class can have constructor and it gets invoked when a class, which implements interface, is instantiated. (i.e. object creation of concrete class).
13. A constructor can also invoke another constructor of the same class – By using this(). If you want to invoke a parameterized constructor then do it like this: this(parameter list).

Private Constructors:
A private constructor is used in a special type of the class called singleton Class. A singleton class is one which can produce only single object at a time. i.e. Not more than one object of the singleton class can be created at the same time.
 Using private constructor we can ensure that no more than one object can be created at a time. By providing a private constructor you prevent class instances from being created in any place other than this very class. We will see in the below example how to use private constructor for limiting the number of objects for a singleton class.

Example of Private Constructor

public class SingleTonClass {
   //Static Class Reference
   private static SingleTonClass obj=null;
   private SingleTonClass(){
      /*Private Constructor will prevent 
       * the instantiation of this class directly*/
   }
   public static SingleTonClass objectCreationMethod(){
          /*This logic will ensure that no more than
           * one object can be created at a time */
          if(obj==null){
              obj= new SingleTonClass();
          }
        return obj;
   }
   public void display(){
          System.out.println("Singleton class Example");
   }
   public static void main(String args[]){
          //Object cannot be created directly due to private constructor 
        //This way it is forced to create object via our method where
        //we have logic for only one object creation
          SingleTonClass myobject= SingleTonClass.objectCreationMethod();
          myobject.display();
   }
}
Output:
Singleton class Example

Can we use static constructor in JAVA
Have you heard of static constructor in Java? I guess yes but the fact is that they are not allowed in Java. A constructor can not be marked as static in Java.  Before I explain the reason let’s have a look at the following piece of code:
public class StaticTest
{
     /* See below - I have marked the constructor as static */
     public static StaticTest()
     {
         System.out.println("Static Constructor of the class");
     }
     public static void main(String args[])
     {
         /*Below: I'm trying to create an object of the class
          *that should invoke the constructor
          */
         StaticTest obj = new StaticTest();
     }
}
Output: You would get the following error message when you try to run the above java code.
“modifier static not allowed here”




Difference between Constructor and Method
I know I should have mentioned it at the beginning of this guide but I wanted to cover everything in a flow. Hope you don’t mind :)
1.  The purpose of constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code.
2.  Constructors cannot be abstract, final, static and synchronised while methods can be.
3.  Constructors do not have return types while methods do.