Back to course

The this Keyword and Instance Variables

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 17: The this Keyword and Instance Variables

The this keyword is a reference to the current object—the object whose method or constructor is currently being executed.

1. Accessing Instance Variables

The primary use of this is to distinguish between instance variables (fields) and local variables (like method parameters) when they share the same name.

java public class User { // Instance variable (Field) private String name;

// Parameterized constructor, where 'name' parameter shadows the field 'name'
public User(String name) {
    // Without 'this', Java would assign the parameter 'name' to itself.
    // 'this.name' refers to the instance variable.
    this.name = name; 
}

public void printName() {
    System.out.println(this.name); // Using 'this' explicitly for clarity
}

}

2. Calling Other Constructors (Constructor Chaining)

If a class has multiple constructors, you can use this() to call another constructor from within the current constructor. This is called constructor chaining and helps avoid code duplication.

java public class Product { String name; double price;

// Full Constructor
public Product(String name, double price) {
    this.name = name;
    this.price = price;
}

// Simplified Constructor (uses default price of 0.0)
public Product(String name) {
    // Calls the first constructor: 
    this(name, 0.0); 
}

}

Rule: If you use this() to call another constructor, it must be the very first statement in the constructor body.