this keyword in java [#3]

this keyword in java [#3]

Recap

In the previous articles, we discussed what Object-Oriented Programming is, objects, classes and respective constructors as well as how to access members of a class. We also saw examples of these concepts in the previous two articles;

Today, we shall look at the "this" keyword in java and why it useful

this keyword

In java, this keyword is used to refer to the current object inside a method or also a constructor.

class Animal {
    int instanceVariable;

    Animal(int instanceVariable) {
          this.instanceVariable = instVariable;
          System.out.println("the this reference =" + this);
   }

public static void main(String[] args) {
      Animal age = new Animal(7);
      System.out.println("the object reference =" + age);
       }
}

Output:

the this reference = Animal@78gd345f
the object reference = Animal@78gd345f

This example above, the object we created named age of the class Animal and once we print the reference to the object and this keyword of the class. In this, we see that the reference of both age and this is the same meaning this is nothing but the reference to the current object.

Use of the this keyword

1. Ambiguity variable names

Not only in Java but also other programming languages, it is not allowed to declare two or more variables having the same name inside a scope that is class or method. But however instance variables and parameters may have the same name without using the "this" keyword.

class Exam {
    // instance variable
    int tm;

    // parameter
    Exam(int tm){
              tm =  tm;
    }

     public static void main(String[] args) {
               Exam examOne = new Exam(3);
               System.out.println("examOne.tm = " examOne.tm);
    }
}
Output:
examOne.tm = 0

In this example above, we have passed 3 to the constructor but we are getting 0 as an output and this is because the Java compiler is getting confused because of the ambiguity in names between instance the variable and the parameter.

Rewriting the above code with the this keyword.

class Exam {

    int tm;
    Exam(int tm){
        this.tm = tm;
    }

    public static void main(String[] args) {
        Exam oj = new Exam(3);
        System.out.println("oj.tm = " + oj.tm);
    }
}

Output:

oj.tm = 3

In this case above, we are getting the expected output. This is because when the constructor is called, this inside the constructor is replaced by the object oj that has called the constructor. Hence the tm variable is assigned value 3.

Also, if the name of the parameter and instance variable is different, the compiler will automatically append the this keyword. For example the code below:

class Exam {
    int size;

    Exam(int p) {
        size = p;
    }
}

is equivalent to:

class Exam {
    int size;

    Exam(int p) {
        this.size = p;
    }
}

This with Getters and Setters

Another common use of this keyword is in setters and getters methods of a class. For example:

class Main {
   String name;

   // setter method
   void setName( String name ) {
       this.name = name;
   }

   // getter method
   String getName(){
       return this.name;
   }

   public static void main( String[] args ) {
       Main obj = new Main();

       // calling the setter and the getter method
       obj.setName("Toshiba");
       System.out.println("obj.name: "+obj.getName());
   }
}

Output:

obj.name: Toshiba

Here, we have used this keyword:

  • to assign value inside the setter method
  • to access value inside the getter method

One of the huge advantages of this() is to reduce the amount of duplicate code. However, we should be always careful while using this().

This is because calling constructor from another constructor adds overhead and it is a slow process. Another huge advantage of using this() is to reduce the amount of duplicate code.

Note: Invoking one constructor from another constructor is called explicit constructor invocation.

Passing this as an Argument

We can use this keyword to pass the current object as an argument to a method. For example,

class ThisExample {
    // declare variables
    int x;
    int y;

    ThisExample(int x, int y) {
       // assign values of variables inside constructor
        this.x = x;
        this.y = y;

        // value of x and y before calling add()
        System.out.println("Before passing this to addTwo() method:");
        System.out.println("x = " + this.x + ", y = " + this.y);

        // call the add() method passing this as argument
        add(this);

        // value of x and y after calling add()
        System.out.println("After passing this to addTwo() method:");
        System.out.println("x = " + this.x + ", y = " + this.y);
    }

    void add(ThisExample o){
        o.x += 2;
        o.y += 2;
    }
}

class Main {
    public static void main( String[] args ) {
        ThisExample obj = new ThisExample(1, -2);
    }
}

Output:

Before passing this to addTwo() method:
x = 1, y = -2
After passing this to addTwo() method:
x = 3, y = 0

In the above example, inside the constructor ThisExample(), notice the line,

add(this);

Here, we are calling the add() method by passing this as an argument. Since this keyword contains the reference to the object obj of the class, we can change the value of x and y inside the add() method.

For a further and more deep explanation about Object Oriented Programming, check out this wonderful playlist. Object Oriented Programming in Java by Kunal Kushwaha.

Feel free to connect with me on Linkedin, github and Twitter thank you.