Constructors in Java

 
 

A constructor initializes an object when it creates. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Every time an object is created using the new() keyword, at least one constructor is called.

ConstructorDemo demo = new ConstructorDemo();

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. Let me explain constructor with the help of a simple program. Here I have created a class ConstructorDemo, created its constructor and then create the object demo which will in turn will call the constructor too.

//Create a Class ConstructorDemo 
public class ConstructorDemo   
{ 
   int x;
 //Create a Constructor for class ConstructorDemo 
   ConstructorDemo()
   {
                   x=24;
   }
         public static void main(String[] args) {
            
                //Create an object of class Constructor and will call the constructor
                 ConstructorDemo demo = new ConstructorDemo();
                  System.out.println("Value of x: "+demo.x);
      }
} 

Output
Value of x:24

Things to remember for a Constructor:-

  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

No Argument Constructor – Here, constructor does not have any argument.

public class DefaultConstructorStudent {
    String Name;
     DefaultConstructorStudent()
    {
            System.out.println("Display details of Student");
       }
      public static voidmain(String[] args) {
           DefaultConstructorStudent stud = newDefaultConstructorStudent();
     }
}

Output
Display details of Student

Parameterized Constructor – A constructor that has a specific number of parameters called a parameterized constructor.

In this example, I have a parameterized constructor with two parameters Name and RollNo. While creating the objects stud1 and stud2, I have passed two arguments so that this constructor gets invoked after creation of stud1 and stud2.

public class ParameterizedStudent {
    String Name;
    int RollNo;
ParameterizedStudent(String New_Name,int New_RollNo)

     {
          Name = New_Name;
          RollNo = New_RollNo;
     }
 
   void DisplayInformation()
   {
        System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo);
   }
        public staticvoid main(String[] args) {
 
            ParameterizedStudent stud1 = newParameterizedStudent("TOM",001);
            ParameterizedStudent stud2 = newParameterizedStudent("MIKE",002);
            stud1.DisplayInformation();
            stud2.DisplayInformation();              
       }
}
 
Output 
Name: TOM, Roll_No: 1
Name: MIKE, Roll_No: 2

Constructor Overloading – This is same as method overloading. Here will have more than one constructor with different parameter lists. Constructors overloaded if they have either different number or parameters, different data type of parameters or different sequence of parameters.

public class ConstructorOverloading {
      String Name;  
      int RollNo;
      int Age;

      //Constructor 1 
      ConstructorOverloading(String New_Name, int New_RollNo, int New_Age)
      {
          Name  = New_Name;
          RollNo = New_RollNo;
          Age = New_Age;
      }

      //Constructor 2
       ConstructorOverloading(int R, int A)
       { 
           RollNo = R;
           Age = A;              
       }

      //Constructor 3 
       ConstructorOverloading(String SName, int SRollNo)
       {
           Name = SName;
           RollNo =SRollNo;
       }
       voidDisplayInformation()
       {
            System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo+","+"Age: "+Age);
       }

      public static void main(String[] args) {
        ConstructorOverloading stud1 = newConstructorOverloading("TOM",001, 20);
        ConstructorOverloading stud2 = newConstructorOverloading(002,21);
        ConstructorOverloading stud3 = newConstructorOverloading("MIKE",003);
        stud1.DisplayInformation();
        stud2.DisplayInformation();
        stud3.DisplayInformation();
     }
}

Output
Name: TOM, Roll_No: 1,Age: 20
Name: null, Roll_No: 2,Age: 21
Name: MIKE, Roll_No: 3,Age: 0

3 thoughts on “Constructors in Java

  1. The concept of overloading is same for both method or constructor. Overloading means same method or constructor can be used in different forms. I'll create a separate blog on method overloading to explain it in detail. Please keep on watching the space for more details.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s