this Keyword in Java
beginner· OOP · Classes & Objects
Problem
The this keyword refers to the current object a constructor or method is running on — it's most often needed when a parameter is deliberately given the same name as the field it initializes.
Write a Student constructor whose parameter is named the same as the field it sets, and use this to tell them apart.
Input
name = "Aditi"
Output
Student name: Aditi
Java Program
Java
class Student {
String name;
Student(String name) {
this.name = name; // this.name is the field; name alone is the parameter
}
}
public class ThisKeywordDemo {
public static void main(String[] args) {
Student student = new Student("Aditi");
System.out.println("Student name: " + student.name);
}
}Output
Student name: Aditi
Core Logic
Naming the constructor parameter identically to the field it sets is convenient to read, but requires this.name to specifically mean the field, since plain name would just refer to the parameter.
How It Works
- 1
Student(String name)declares a parameter namedname, deliberately matching the field's own name. - 2Inside the constructor,
nameby itself always refers to the parameter — the field is shadowed as long as the parameter is in scope. - 3
this.name = name;usesthisto reach the object's own field specifically, assigning the parameter's value to it. - 4Without
this., writing justname = name;would assign the parameter to itself and leave the field untouched.
Constructing
new Student("Aditi") runs this.name = name;, correctly setting the object's field to "Aditi".💡
Key Point: this. is only strictly necessary here because the parameter and field share a name — with a differently-named parameter, like studentName, plain assignment would work without it.
Key Concepts
this keywordconstructor parameterfield disambiguation