Java this Keyword
The this keyword in Java refers to the current object instance within
a class. It is commonly used inside constructors and methods to distinguish
between class attributes (fields) and parameters that share the same name,
and to enable constructor chaining.
Why Use this in Java?
In object-oriented programming, method parameters often have the same names
as class attributes. In such cases, the parameter temporarily hides the
attribute. The this keyword explicitly refers to the current object’s
attribute.
Think of it as:
this.attribute = parameter; → “assign the parameter value to this object’s
attribute”
Accessing Class Attributes with this
When attribute and parameter names match, use this to refer to the
attribute.
public class Account {
int balance;
public Account(int balance) {
this.balance = balance; // refers
to class attribute
}
public static void main(String[] args) {
Account acc = new Account(5000);
System.out.println("Balance: " +
acc.balance);
}
}
Output
Balance: 5000
Without this, balance = balance; would assign the parameter to itself,
leaving the attribute uninitialized (0).
Using this in Methods
The this keyword can also access attributes inside instance
methods.
public class Employee {
String name;
public void setName(String name) {
this.name = name; // distinguish
field from parameter
}
public void display() {
System.out.println("Employee: " +
this.name);
}
public static void main(String[] args) {
Employee e = new Employee();
e.setName("Arun");
e.display();
}
}
Calling One Constructor from Another (this())
The this() syntax allows a constructor to call another constructor in the
same class. This avoids code duplication and enables default
values.
Rule: this() must be the first statement in a
constructor.
public class Vehicle {
int year;
String model;
// Constructor with one parameter
public Vehicle(String model) {
this(2024, model); // call another
constructor
}
// Constructor with two parameters
public Vehicle(int year, String model) {
this.year = year;
this.model = model;
}
public void showInfo() {
System.out.println(year + " " +
model);
}
public static void main(String[] args) {
Vehicle v1 = new Vehicle("Kia Seltos");
// default year
Vehicle v2 = new Vehicle(2020, "Honda
City");
v1.showInfo();
v2.showInfo();
}
}
Output
2024 Kia Seltos
2020 Honda City