Java this Keyword
Java this Keyword: this Variable, this Method, this Constructor (With Examples)
✨ Quick Summary
In this post, you’ll learn what the this keyword means in Java and why it is used. We will cover this variable, this method, and this constructor with simple examples.
In our previous post, we learned about the static keyword in Java. Now, let’s learn another very important keyword used in constructors and OOP: this.
1) What is this Keyword in Java?
The this keyword in Java refers to the current object.
✅ Simple meaning: this = the current class object
2) Why Do We Use this Keyword?
We use this keyword mainly for:
- ✅ To differentiate between instance variables and parameters
- ✅ To call current class methods
- ✅ To call current class constructor (constructor chaining)
3) this Keyword to Refer Instance Variable
This is the most common use of this. When constructor parameters have the same name as instance variables, we use this to avoid confusion.
class Student {
String name;
Student(String name) {
this.name = name; // this.name = instance variable
}
void display() {
System.out.println("Name: " + name);
}
}
public class ThisVariableExample {
public static void main(String[] args) {
Student s1 = new Student("Aishwarya");
s1.display();
}
}
4) this Keyword to Call Current Class Method
You can use this to call a method of the same class. It is optional, but useful for clarity.
class Demo {
void show() {
System.out.println("Show method called");
}
void display() {
this.show(); // calling current class method
}
}
public class ThisMethodExample {
public static void main(String[] args) {
Demo d = new Demo();
d.display();
}
}
5) this Keyword to Call Current Class Constructor
You can use this() to call another constructor of the same class. This is called constructor chaining.
⚠️ Important Rule: this() must be the first statement inside the constructor.
class Test {
Test() {
System.out.println("Default constructor");
}
Test(int x) {
this(); // calls default constructor
System.out.println("Parameterized constructor: " + x);
}
}
public class ThisConstructorExample {
public static void main(String[] args) {
Test t = new Test(100);
}
}
6) Interview Notes (Very Important)
- ✅ this refers to current object
- ✅ Used to resolve variable name conflict
- ✅ Used in constructor chaining using this()
- ⚠️ this() must be the first line in constructor
Conclusion
This keyword is used in Java OOP, especially in constructors and instance variables. You will make extensive use of this keyword in your real-life programming when working with constructors.
Next Post: Java super Keyword (super variable, super method, super constructor)

Great work
ReplyDelete