DEV Community

Cover image for Mastering THIS Keyword in Java: A Key to Clean and Effective Code
Arshi Saxena
Arshi Saxena

Posted on

Mastering THIS Keyword in Java: A Key to Clean and Effective Code

The this keyword in Java serves as a reference to the current object. It enhances code readability and ensures precise control over constructors, instance variables, and method calls. This article explores the versatility of this with multiple examples.


1. Referencing the Current Class Instance

We use this to return the current object or instance of the class.

package this_keyword;

public class ClassInstance {

    private int a, b;

    public ClassInstance(int x, int y) { 
        a = x; 
        b = y; 
    }

    private ClassInstance get() {
        // Using 'this' to return the current class instance
        return this;
    }

    @Override
    public String toString() {
        return "ClassInstance [a=" + a + ", b=" + b + "]";
    }

    public static void main(String[] args) {
        ClassInstance obj = new ClassInstance(10, 20);
        System.out.println(obj.get()); // Output: ClassInstance [a=10, b=20]
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

In this example, the get() method uses THIS to return the current instance of the ClassInstance class. This technique is useful when working with method chaining or builders.

The toString() method is overridden to provide a readable representation of the object, displaying its instance variables. This is especially handy for debugging and logging, as it allows you to easily see the values of a and b when the object is printed.


2. Constructor Chaining with this()

Constructor chaining in Java allows one constructor to call another constructor within the same class using this(). This feature promotes code reusability, reduces redundancy, and ensures concise initialization logic.

Importantly, this() must be the first statement in the constructor if chaining is being done; otherwise, it will lead to a compile-time error.

Example Code

package constructor_chaining;

// *Order of calls marked*
public class SameClassConstructorChaining {

    // If used, this() has to be the first statement 
    public SameClassConstructorChaining() {
        this(5); // *2*
        System.out.println("Default Constructor"); // *6*
    }

    public SameClassConstructorChaining(int x) {
        this(x, 10); // *3*
        System.out.println("Value of x: " + x); // *5*
    }

    public SameClassConstructorChaining(int x, int y) {
        System.out.println("Sum: " + (x + y)); // *4*
    }

    public void displayText() {
        System.out.println("Constructor Chaining Achieved!"); // *8*
    }

    public static void main(String[] args) {
        SameClassConstructorChaining obj = new SameClassConstructorChaining(); // *1*
        obj.displayText(); // *7*
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow

  1. Main Method: The execution begins with new SameClassConstructorChaining() (marked as 1). This invokes the Default Constructor.
  2. Default Constructor: It executes the line this(5) (marked as 2), transferring control to the One-Parameter Constructor.
  3. One-Parameter Constructor:
    • Receives x = 5 and calls this(x, 10) (marked as 3), transferring control to the Two-Parameter Constructor.
  4. Two-Parameter Constructor:
    • This constructor executes the line that computes and prints the sum of 5 and 10 (marked as 4).
  5. Returning to One-Parameter Constructor:
    • After executing the Two-Parameter Constructor, control returns to the One-Parameter Constructor, which then prints Value of x: 5 (marked as 5).
  6. Returning to Default Constructor:
    • Finally, control goes back to the Default Constructor, which prints Default Constructor (marked as 6).
  7. Display Method: The execution concludes with the call to obj.displayText() (marked as 7), which prints Constructor Chaining Achieved! (marked as 8).

3. Differentiating Instance Variables from Parameters

In Java, shadowing occurs when a local variable (such as a method parameter or a variable defined within a method) has the same name as an instance variable of the class.

When this happens, the local variable "shadows" the instance variable, meaning that within the scope of the local variable, the instance variable is hidden.

As a result, if you try to reference the variable by its name, the local variable will be used instead of the instance variable.

When parameter names shadow instance variables, this helps differentiate between them.

package this_keyword;

public class InstanceVariables {

    private int a, b;

    public InstanceVariables(int a, int b) {
        // Using 'this' to distinguish instance variables from parameters
        this.a = a;
        this.b = b;
    }

    @Override
    public String toString() {
        return "InstanceVariables [a=" + a + ", b=" + b + "]";
    }

    public static void main(String[] args) {
        InstanceVariables obj = new InstanceVariables(2, 4);
        System.out.println(obj); // Output: InstanceVariables [a=2, b=4]
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

Using this clarifies that this.a refers to the instance variable, not the constructor parameter a. This is essential when working with similar names for variables and parameters.


4. Passing the Current Object as a Parameter

We can pass the current instance of a class as a parameter using this.

package this_keyword;

public class MethodParameter {

    private int a, b;

    public MethodParameter() {
        a = 10;
        b = 20;
    }

    private void display(MethodParameter obj) {
        System.out.println("a = " + obj.a + ", b = " + obj.b);
    }

    private void get() {
        // Passing 'this' as a parameter to display() method
        display(this);
    }

    public static void main(String[] args) {
        MethodParameter obj = new MethodParameter();
        obj.get(); // Output: a = 10 , b = 20
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

In this example, this is passed as an argument to the display() method, allowing it to access the same instance’s variables.


Key Takeaways

  • Referencing the Current Instance: Use this to refer to the current class instance or object.
  • Constructor Chaining: Use this() to call another constructor within the same class.
  • Distinguishing Variables: Use this to differentiate between instance variables and parameters.
  • Passing the Current Object: Use this to pass the current object as a parameter.

Conclusion

The this keyword provides clarity and control when working with class instances, constructors, and methods in Java. Mastering its use can lead to more readable, efficient, and maintainable code.

This post is just the beginning! In this series, we’ll explore other powerful keywords in Java, uncovering their inner workings and practical uses. Stay tuned for upcoming posts as we continue this journey through Java’s core concepts! 🚀


Related Posts

Happy Coding!

Top comments (0)