When, Where and Why to use ‘this’ keyword in Java?

When, Where and Why to use ‘this’ keyword in Java?

To understand the role of ‘this’ in Java-based Object-Oriented Programming, you need to understand the series of events that happen before the ‘this’ keyword comes into the picture. If you already know that stuff, feel free to move forward directly to the desired section of this article.

What are Classes and Objects?

Class is a template that Objects use to come into existence. An Object’s properties and functions are all derived from its Class.

Let’s understand with the help of an example:

If you want to store data of 5 employees. For salary numbers, you can do it in an array, like int [] salary = new int [5]; Now you want to store employee names, you can do String [] name = new String [5]; And for years of experience, you can do float [] exp = new float [5]; But how do we combine all three above data types into a single entity, a custom datatype? We can do it via Class.

class Employee { 
    String name;  
    int salary; 
    float exp; 
}

How do we create multiple Objects of different employees by using this Class?

20220207_091119_0000.png

Before that, we need to understand how do we access the Class properties as all Employee Objects need these properties to come into existence and store data about themselves. We access/bind them with the Dot operator.

The Role of Dot Operator

Dot Operator links the reference variable (employee1, employee2, employee3) with the instance variable (name, salary, exp).

For example, employee1.name will represent Michael.

20220207_091119_0001.png

But there’s a problem. If you declare Employee employee1; and type System.out.println(employee1.name); The console should have shown ‘null’ as the default value. Instead, the compiler will give an error that variable employee1 has not been initialized and does not acquire any space in the heap memory.

Here the ‘new’ keyword comes in.

The Role of ‘new’ Keyword

To create the Objects, you need the ‘new’ keyword. The ‘new’ keyword initializes, means allocates memory for the Object at runtime.

Employee employee1 = new Employee ();

20220207_123814_0000.png

Now if you type System.out.println(employee1.name); it will print ‘null’ in the console, which is the default value of any String variable. Now we can successfully allocate value with the dot operator.

employee1.name = “Michael”; 
employee1.salary = 150000; 
employee1.exp = 2.5f; 

employee2.name = “Emily”; 
employee2.salary = 180000; 
employee2.exp = 3.5f;

But did you notice this process of binding is quite repetitive? We have to write employee1 again and again. We can use a shortcut and allocate data to their respective instance variables (like Michael to name and 150000 to salary).
Here the Constructor comes in.

The Role of a Constructor

A Constructor is a special built-in type of Function in the Class that runs and defines what happens when we create an Object. We can allocate the data by writing it in the argument of a constructor function. If we don’t write the data, the constructor will bind default values (like null, 0 and 0.0) to the Object.
For Constructor to bind the values written in the brackets like new Employee (“Michael”, 150000, 2.5); we need to write the Constructor function inside the Class like:

class Employee { 
         String name;  
         int salary; 
         float exp; 

         Employee () { 
                 employee1.name = “Michael”; 
                 employee1.salary = 150000; 
                 employee1.exp = 2.5f; 
         } 
}

But this will give you an error. Class is a template to create multiple Objects. You can’t mention only one employee or custom object inside the Class. You won’t make a separate constructor for each employee as that would be counterproductive and repetitive.

We need a way to add values to properties of multiple Objects with the same Constructor. We need one word to access every Object and bind the Constructor argument with the Class properties. So that the Constructor can automatically replace that word like word.name with Object names like employee1.name, employee2.name or employee3.name.

Here the keyword ‘this’ comes into the picture.

The Role of ‘this’ keyword

The ‘this’ keyword helps us bind the arguments of a Constructor function like new Employee (“Michael”, 150000, 2.5); with the respective properties like name, salary, exp present inside the Class to be inherited by all Objects.
With the ‘this’ keyword, we can create as many employee Objects as we want without repeatedly writing code like employee1.name = “Michael”, employee2.name = “Emily”, employee3.name = “Ryan”.

class Employee { 
             String name;  
             int salary; 
             float exp; 

             Employee (String name, int salary, float exp) { 
                             this.name = name; 
                             this.salary = salary; 
                             this.exp = exp; 
             } 
}

In the code above, this.name = name; doesn’t have to be that way. You can write a different argument name in the Constructor, for example:

class Employee { 
          String name;  
          int salary; 
          float exp; 

          Employee (String empName, int salaryOfEmployee, float expYears) { 
                          this.name = empName; 
                          this.salary = salaryOfEmployee; 
                          this.exp = expYears; 
          } 
}

20220207_091308_0000.png

We can also pass desired custom functions inside the Class like:

class Employee { 
        String name;  
        int salary; 
        float exp; 

        void greeting () { 
              System.out.println (“Hello everyone, my name is+ this.name);
        }

        Employee (String empName, int salaryOfEmployee, float expYears) { 
                this.name = empName; 
                this.salary = salaryOfEmployee; 
                this.exp = expYears; 
        } 
}

If you write employee1.greeting(); it will print “Hello everyone, my name is Michael”. If you write employee2.greeting(); it will print “Hello everyone, my name is Emily”.

Conclusion

From the series of events above, we understood that the 'this' keyword is the last step in the series that helps us create unlimited Objects with the help of a Class and its Constructor function. The 'this' keyword replaces itself with the Object name like employee1, employee2, employee3 and binds it to the Class Properties like name, salary, experience with the help of dot operator. We can use the 'this' keyword in self-made, custom functions inside the Class for attaching the different assigned values to Class properties for various Objects as we saw in the greeting(); function.

Thanks for reading! :)

Did you find this article valuable?

Support Kshitij Sharma by becoming a sponsor. Any amount is appreciated!