this keyword in java

Java this Keyword with Example

In this tutorial, we will learn about this keyword in Java, as well as how and where to use it with examples.

this Keyword

‘this’ keyword is used in Java to refer to the current object within a method or a constructor.

  • this keyword in Java can be used in a variety of ways. This is a reference variable in Java that refers to the current object.

As an example:

class Main {
    int sample;

    Main(int sample){
        this.sample = sample;
        System.out.println("this reference = " + this);
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("object reference = " + obj);
    }
}

Output:

this reference = Main@23fc625e
object refrence = Main@23fc625e

  • In the preceding example, we created an object of the class Main called obj. We then print the reference to the object obj as well as the class’s this keyword.
  • We can see here that the references of both obj and this are the same. This means that this is nothing more than a reference to the current object.

Uses of this Keyword

This keyword is commonly used in a variety of scenarios.

‘this’ is used for ambiguous variable names.

It is not permitted in Java to declare two or more variables with the same name within the same scope (class scope or method scope). Instance variables and parameters, on the other hand, may have the same name. As an example:

class MyClass {
// instance variable
int age;
// parameter

MyClass(int age){
age = age;
}
}
  • The instance variable and the parameter in the preceding programme have the same name: age. Due to name ambiguity, the Java compiler is perplexed in this case.
  • In such a case, we employ this keyword. As an example,

Let’s start with an example that doesn’t include this keyword:

class Main {
int age; Main(int age){
age = age;
}
public static void main(String[] args) {
Main obj = new Main(8);
System.out.println(“obj.age = ” + obj.age);
}
}

Output:

obj.age = 0

  • In the preceding example, we passed the constructor  the value 8. However, we get a 0 as an output. This is due to the ambiguity in the names of the instance, variable, and parameter, which causes the Java compiler to become confused.

this keyword in java,this keyword in java,this keyword in java,this keyword injava,this keyword in java,this keyword in java,this keyword in java,this keyword in java,

Now, let’s rewrite the preceding code with this keyword.

class Main {

    int age;
    Main(int age){
        this.age = age;
    }

    public static void main(String[] args) {
        Main obj = new Main(8);
        System.out.println("obj.age = " + obj.age);
    }
}

Output:

obj.age = 8
  • We are now getting the expected results. This is because when the constructor is called, the object obj that called the constructor replaces this inside the constructor. As a result, the age variable is assigned the value 8.
  • In addition, if the names of the parameter and instance variable differ, the compiler appends this keyword automatically. For instance, consider the following code:

class Main {
int age;
Main(int i) {
age = i;
}
}

//is the same as:
class Main {
int age;
Main(int i) {
this.age = i;
}
}

this with Getters and Setters

this keyword is also commonly used in a setters and getters methods. As an 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("DevelopersDome");
       System.out.println("obj.name: "+obj.getName());
   }
}

Output:

obj.name : DevelopersDome

In this case, we’ve used the following keyword:

  • inside the setter method, to assign a value
  • to gain access to a value within the getter method

Using this in Constructor Overloading

  • When working with constructor overloading, we may need to call one constructor from another. We can’t call the constructor explicitly in this case. Instead, we must employ this keyword.
  • this keyword is used in a different way here. That is to say ().

Let’s look at an example:

class Sample {

    private int a, b;

    // constructor with 2 parameters
    private Sample( int i, int j ){
        this.a = i;
        this.b = j;
    }

    // constructor with single parameter
    private Sample(int i){
        // invokes the constructor with 2 parameters
        this(i, i); 
    }

    // constructor with no parameter
    private Sample(){
        // invokes the constructor with single parameter
        this(0);
    }

    @Override
    public String toString(){
        return this.a + " + " + this.b + "i";
    }

    public static void main( String[] args ) {
  
        // creating object of Complex class
        // calls the constructor with 2 parameters
        Sample c1 = new Sample(4, 5); 
    
        // calls the constructor with a single parameter
        Sample c2 = new Sample(5);

        // calls the constructor with no parameters
        Sample c3 = new Sample();

        // print objects
        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
    }
}

Output:

4 + 5i
5 + 5i
0 + 0i

Note: It is important to note that invoking one constructor from another is referred to as explicit constructor invocation.

this is used as an argument.

this keyword can be used to pass the current object as an argument to a method. As an example:

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

    Sample(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 ) {
        Sample obj = new Sample(1, -2);
    }
}

Output:

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

Take note of the line inside the constructor Sample() in the preceding example.

add(this);

By passing this as an argument, we are calling the add() method. Because this keyword contains a reference to the class’s object obj, we can change the values of x and y within the add() method.

You may like:

Constructor in java with Example

Hope this article will guide you to recognize all about the Java this keyword with Example that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has 5 Comments

Leave a Reply