Constructor

Constructor

In the previous blog, we have seen Objects and Classes in Java, how to define classes, the creation of objects, etc. So In this blog, we will cover constructors, various types of constructors, the 'this' keyword and much more.

Let's start with the example we have seen in the classes and objects blog, i.e "class Account"

class Account{
    String accountName;
    int accountNumber;
    float balance;
}

As we have seen in the last blog to access properties or functions of a class through objects we use the "dot" operator. Let's say we have created an object named account1 like,

Account account1 = new Account(); //object account1 of class Account

Now we try to access the accountNumber of the account1 object, to access we follow the rule object_name.property_name. So by using this accessing syntax we try to print the properties of the object created.

for the above code, we will get the following output:

null
0
0.0

It is evident as the properties are not initialized with values, so we are getting the default values for string, int and float. so To access and set the value, we can do so by using "dot" operator.

In the above code, we assign values to all properties of the class and display them using the dot operator. This is the proper implementation if we have one object, what if we needed to create 50 objects of the same class, then this approach is not feasible as we would need to set values for all 50 objects also it will make our code lengthy. So to overcome this scenario, we have constructors in Java. we can send values of its properties while creating the objects, for this purpose let us understand how to create constructors.

Constructors are used to pass values to the object while instantiating the object.

The following are things one needs to keep in mind while creating a constructor:

  • constructors are part of the class.

  • constructor is named the same as the class name.

  • constructor is followed by open and closed brackets to pass parameters.

  • We can have more than one constructor in a single class.

For example, In our case:

class Account{
    String accountName;
    int accountNumber;
    float balance;

    //constructor part below
   Account(String accountName, int accountNumber,float balance){
            this.accountName = accountName;
            this.accountNumber = accountNumber;
            this.balance = balance;
    }
}

Please for now ignore the "this" keyword, we will see it later. But you can notice the constructor name is the same as the class "Account", it has open and closed brackets and some parameters in it followed by curly braces. In the body of the constructor, we are setting the class property values with the constructor's parameters.

Now we can write only a single line in the main, to call objects and pass values.

Account account1 = new Account("John",215,4500);
//Try to print the objects properties
System.out.println(account1.accountName);
System.out.println(account1.accountNumber);        System.out.println(account1.balance);

The output for the above main code will be as follow:

John
215
4500.0

Types of Constructors

  • Default constructor

  • Parameterized constructor

  • copy constructor

      class Account{
          String accountName;
          int accountNumber;
          float balance;
    
         Account(){
          //Default constructor.
          }
          Account(String accountName, int accountNumber,float balance){
          //Parameterized Constructor.
          }
          Account(Account account){
          //Create copy of an existing object of the class.
          }
      }
    

    Now we are at the end of the tunnel, let us take our final topic "this" keyword.

This keyword

The "This" keyword in Java is a reference variable that refers to the current object.

This is used to refer to the current instance variable of objects, this is used to resolve ambiguity. For reference, you can go through our above code example where we used this keyword to refer to the current instance and assign passed parameters.

Thank you for reading. Hope you understood the concepts.

#JustJavaThings

Did you find this article valuable?

Support Abhishek Madankar by becoming a sponsor. Any amount is appreciated!