Java this Keyword
Reference to the current object instance
đ What is the 'this' Keyword?
The 'this' keyword refers to the current object instance. It helps distinguish between class attributes and parameters with the same name, and allows objects to reference themselves in methods and constructors.
class Person {
String name;
public Person(String name) {
this.name = name; // this.name refers to class attribute
}
}
Uses of 'this' Keyword
Attribute Access
Distinguish class attributes from parameters
this.name = name;
Method Calls
Call other methods in the same class
this.displayInfo();
Constructor Chaining
Call other constructors
this("Default", 0);
Return Current Object
Return the current object instance
return this;
đš Resolving Name Conflicts
The most common use of 'this' is to distinguish between class attributes and parameters:
// Employee.java
class Employee {
String name;
int id;
String department;
double salary;
// Without 'this' - CONFUSING!
public void setBadExample(String name, int id) {
name = name; // This assigns parameter to itself!
id = id; // This doesn't change the class attribute!
}
// With 'this' - CLEAR!
public void setEmployeeInfo(String name, int id, String department, double salary) {
this.name = name; // this.name = class attribute
this.id = id; // name = parameter
this.department = department;
this.salary = salary;
System.out.println("Employee info updated for: " + this.name);
}
// Constructor using 'this'
public Employee(String name, int id, String department, double salary) {
this.name = name;
this.id = id;
this.department = department;
this.salary = salary;
System.out.println("New employee created: " + this.name);
}
// Method to display employee info
public void displayEmployee() {
System.out.println("=== Employee Details ===");
System.out.println("Name: " + this.name);
System.out.println("ID: " + this.id);
System.out.println("Department: " + this.department);
System.out.println("Salary: $" + this.salary);
}
}
// EmployeeExample.java
public class EmployeeExample {
public static void main(String[] args) {
// Create employee using constructor
Employee emp1 = new Employee("Alice Johnson", 1001, "Engineering", 75000.0);
emp1.displayEmployee();
System.out.println();
// Create another employee and set info
Employee emp2 = new Employee("Bob Smith", 1002, "Marketing", 65000.0);
emp2.displayEmployee();
System.out.println();
// Update employee info
emp2.setEmployeeInfo("Robert Smith", 1002, "Sales", 70000.0);
emp2.displayEmployee();
}
}
Output:
New employee created: Alice Johnson === Employee Details === Name: Alice Johnson ID: 1001 Department: Engineering Salary: $75000.0 New employee created: Bob Smith === Employee Details === Name: Bob Smith ID: 1002 Department: Marketing Salary: $65000.0 Employee info updated for: Robert Smith === Employee Details === Name: Robert Smith ID: 1002 Department: Sales Salary: $70000.0
đš Constructor Chaining with 'this'
Use 'this()' to call other constructors in the same class:
// Product.java
class Product {
String name;
String category;
double price;
int quantity;
boolean inStock;
// Main constructor with all parameters
public Product(String name, String category, double price, int quantity, boolean inStock) {
this.name = name;
this.category = category;
this.price = price;
this.quantity = quantity;
this.inStock = inStock;
System.out.println("Full product created: " + this.name);
}
// Constructor with name, category, and price (calls main constructor)
public Product(String name, String category, double price) {
this(name, category, price, 0, false); // Call main constructor
System.out.println("Basic product created: " + this.name);
}
// Constructor with just name (calls 3-parameter constructor)
public Product(String name) {
this(name, "General", 0.0); // Call 3-parameter constructor
System.out.println("Simple product created: " + this.name);
}
// Default constructor (calls 1-parameter constructor)
public Product() {
this("Unknown Product"); // Call 1-parameter constructor
System.out.println("Default product created");
}
// Method to display product info
public void displayProduct() {
System.out.println("=== Product Information ===");
System.out.println("Name: " + this.name);
System.out.println("Category: " + this.category);
System.out.println("Price: $" + this.price);
System.out.println("Quantity: " + this.quantity);
System.out.println("In Stock: " + this.inStock);
System.out.println();
}
// Method to restock product
public void restock(int quantity) {
this.quantity += quantity;
this.inStock = this.quantity > 0;
System.out.println("Restocked " + this.name + " with " + quantity + " units");
}
}
// ProductExample.java
public class ProductExample {
public static void main(String[] args) {
// Using different constructors
Product product1 = new Product();
Product product2 = new Product("Laptop");
Product product3 = new Product("Mouse", "Electronics", 25.99);
Product product4 = new Product("Keyboard", "Electronics", 79.99, 50, true);
// Display all products
product1.displayProduct();
product2.displayProduct();
product3.displayProduct();
product4.displayProduct();
// Restock a product
product3.restock(100);
product3.displayProduct();
}
}
Output:
Full product created: Unknown Product Basic product created: Unknown Product Simple product created: Unknown Product Default product created Full product created: Laptop Basic product created: Laptop Simple product created: Laptop Full product created: Mouse Basic product created: Mouse Full product created: Keyboard === Product Information === Name: Unknown Product Category: General Price: $0.0 Quantity: 0 In Stock: false === Product Information === Name: Laptop Category: General Price: $0.0 Quantity: 0 In Stock: false === Product Information === Name: Mouse Category: Electronics Price: $25.99 Quantity: 0 In Stock: false === Product Information === Name: Keyboard Category: Electronics Price: $79.99 Quantity: 50 In Stock: true Restocked Mouse with 100 units === Product Information === Name: Mouse Category: Electronics Price: $25.99 Quantity: 100 In Stock: true
đš Method Chaining with 'this'
Return 'this' from methods to enable method chaining:
// BankAccount.java
class BankAccount {
String accountHolder;
double balance;
String accountType;
public BankAccount(String holder) {
this.accountHolder = holder;
this.balance = 0.0;
this.accountType = "Checking";
}
// Method that returns 'this' for chaining
public BankAccount deposit(double amount) {
if (amount > 0) {
this.balance += amount;
System.out.println("Deposited $" + amount + " to " + this.accountHolder + "'s account");
}
return this; // Return current object for chaining
}
// Method that returns 'this' for chaining
public BankAccount withdraw(double amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
System.out.println("Withdrew $" + amount + " from " + this.accountHolder + "'s account");
} else {
System.out.println("Invalid withdrawal amount for " + this.accountHolder);
}
return this; // Return current object for chaining
}
// Method that returns 'this' for chaining
public BankAccount setAccountType(String type) {
this.accountType = type;
System.out.println("Account type changed to: " + this.accountType);
return this; // Return current object for chaining
}
// Method to display account info
public BankAccount displayAccount() {
System.out.println("=== Account Information ===");
System.out.println("Holder: " + this.accountHolder);
System.out.println("Balance: $" + this.balance);
System.out.println("Type: " + this.accountType);
System.out.println();
return this; // Return current object for chaining
}
// Method to get balance (doesn't need to return this)
public double getBalance() {
return this.balance;
}
}
// BankExample.java
public class BankExample {
public static void main(String[] args) {
// Create account and use method chaining
BankAccount account = new BankAccount("John Doe");
// Chain multiple method calls
account.deposit(1000.0)
.setAccountType("Savings")
.deposit(500.0)
.withdraw(200.0)
.displayAccount();
// More chaining
account.deposit(300.0)
.withdraw(100.0)
.displayAccount();
System.out.println("Final balance: $" + account.getBalance());
}
}
Output:
Deposited $1000.0 to John Doe's account Account type changed to: Savings Deposited $500.0 to John Doe's account Withdrew $200.0 from John Doe's account === Account Information === Holder: John Doe Balance: $1300.0 Type: Savings Deposited $300.0 to John Doe's account Withdrew $100.0 from John Doe's account === Account Information === Holder: John Doe Balance: $1500.0 Type: Savings Final balance: $1500.0
đš When to Use 'this'
Required Usage:
- Name conflicts: When parameter names match attribute names
- Constructor chaining: Calling other constructors with this()
- Method chaining: Returning current object for fluent interface
Optional but Good Practice:
- Accessing class attributes for clarity
- Calling methods on current object explicitly
- Making code more readable and self-documenting
Remember:
- 'this' refers to the current object instance
- Cannot be used in static methods (no object instance)
- this() must be the first statement in constructor