English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, we will understand the this keyword in Java through examples, how and where to use them.
In Java, the this keyword is used to refer to the current object in a method or constructor. For example,
class Main { int instVar; Main(int instVar){ this.instVar = instVar; 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 = com.ThisAndThat.MyClass@74a14482 Object reference = com.ThisAndThat.MyClass@74a14482
In the above example, we created an object named obj of the Main class. Then, we printed the references to the object of the class obj and the this keyword.
Here, we can see that the references of obj and this are the same. This means that this is just a reference to the current object.
In various cases, the this keyword is usually used.
In Java, it is not allowed to declare two or more variables with the same name within a scope (class scope or method scope). However, instance variables and parameters may have the same name. For example,
class MyClass { // Instance variable int age; // Parameter MyClass(int age){ age = age; } }
In the above program, the instance variable and the parameter have the same name: age. Here, the Java compiler is confused due to the unclear name.
In this case, we use the this keyword. For example,
First, let's look at an example without using the 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:
mc.age = 0
In the above example, we have assigned a value8It is passed to the constructor. However, the 0 we get is the output. This is because the Java compiler is confused due to the unclear names between instance variables and parameters.
Now, let's rewrite the above code using the 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
Now, we have the expected output. This is because when the constructor is called, the content inside the constructor is replaced by the object obj that calls the constructor. Therefore, the age variable is assigned the value of8.
Additionally, if the parameter and instance variable names are different, the compiler will automatically append the this keyword. For example, the code:
class Main { int age; Main(int i) { age = i; } }
It is equivalent to:
class Main { int age; Main(int i) { this.age = i; } }
Another common use of the this keyword is in the class'ssetter and getter methods. 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(); // Call setter and getter methods obj.setName("Seagull"); System.out.println("obj.name: ",+obj.getName()); } }
Output:
obj.name: Seagull
Here, we have used the this keyword:
Assigning values in setter methods
Accessing values in getter methods
When dealing withWhen overloading constructorsWe may need to call a constructor from another constructor. In this case, we cannot explicitly call the constructor. Instead, we must use the this keyword.
Here, we use another form of the this keyword. That is this(). Let's take an example
class Complex { private int a, b; //Constructor with two parameters private Complex(int i, int j) { this.a = i; this.b = j; } //Constructor with a single parameter private Complex(int i) { //Calling constructor with two parameters this(i, i); } //Constructor without parameters private Complex() { //Calling constructor with a single parameter this(0); } @Override public String toString() { return this.a + " + " + this.b + "i"; } public static void main(String[] args) { //Creating an object of the Complex class //Using2parameter calling constructor Complex c1 = new Complex(2, 3); //Calling constructor with a single parameter Complex c2 = new Complex(3); //Calling constructor without parameters Complex c3 = new Complex(); //Printing the object System.out.println(c1); System.out.println(c2); System.out.println(c3); } }
Output:
2 + 3i 3 + 3i 0 + 0i
In the above example, we used the this keyword,
Calling constructor Complex(int i) from constructor Complex(int i, int j)
Calling constructor Complex() from constructor Complex(int i)
Note this line,
System.out.println(c1);
Here, when we print the object c1When, the object is converted to a string. In this process, toString() will be called. Since we have overridden the toString() method in the class, we get the output based on that method.
One of the biggest advantages of this() is that it reduces the amount of duplicate code. However, we should be especially careful when using this().
This is because calling a constructor from another constructor adds overhead, and it is a slow process. Another huge advantage of using this() is reducing the amount of duplicate code.
Note: Calling one constructor from another constructor is called explicit constructor call.
We can use the this keyword to pass the current object as a parameter to a method. For example,
class ThisExample { // declare variables int x; int y; ThisExample(int x, int y) { //Assigning values to variables within the constructor this.x = x; this.y = y; //The values of x and y before calling add() System.out.println("Before passing this to the addTwo() method:"); System.out.println("x = ") + this.x + ", y = " + this.y); //Calling the add() method, passing this as a parameter add(this); //The values of x and y after calling add() System.out.println("After passing this to the 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 the addTwo() method: x = 1, y = -2 After passing this to the addTwo() method: x = 3, y = 0
In the above example, in the constructor ThisExample(), pay attention to the following line:
add(this);
Here, we call the add() method by passing this as a parameter. Since the this keyword contains a reference to the object obj of the class, we can change the values of x and y in the add() method.