this keyword in Java

Free Java courses with 37 real-time projects - Learn Java

The ‘this’ keyword in Java is a fundamental element of object-oriented programming, serving as a reference variable that plays a pivotal role in establishing a strong connection between an object and its associated methods and attributes.

In Java, objects are like the fundamental parts of code, containing both information and actions. When you invoke a method or create an object using a constructor, ‘this’ comes into play, acting as the indispensable link between these objects and the methods that manipulate them.

Think of ‘this’ in Java as a kind of linguistic pointer, similar to how we use “self” in everyday language to refer to ourselves. In the Java context, ‘this’ points to the current instance of a class. It serves as a way to pinpoint and interact with the attributes and methods within an object itself, making it a powerful tool for disambiguating between different instances of a class.

This is particularly useful when objects share the same variable names or when local variables and method parameters overlap with class member variables. By using ‘this’ in Java, you can prevent confusion and make sure the program understands exactly which parts of an object you’re talking about, which helps make your Java code clear and precise. In essence, ‘this’ is a critical component in the art of crafting efficient, maintainable, and well-organized Java applications.

Usages of Java ‘this’ Keyword

The main usages of the ‘this’ keyword in Java are:

1. Referring to Current Class Instance Variables: Within a class, there can be instances where local variables and instance variables share the same name. In such cases, using ‘this’ is a key strategy to distinguish between them. When you preface a variable with ‘this,’ it explicitly refers to the instance variable of the current object. This ensures that the intended instance variable is accessed, and it helps prevent ambiguity.

2. Invoking Current Class Methods: When a method in a class needs to call another method of the same class, ‘this’ is employed. It allows you to invoke methods within the same class without any confusion. This is particularly useful in situations where methods with similar names exist or when you want to explicitly call a method of the current instance.

3. Invoking Current Class Constructors: Similar to invoking methods, ‘this’ is used to call one constructor from another within the same class. This is often seen in constructors with overloaded variants, where one constructor prepares the initial state of an object and delegates it to another constructor for additional customization.

4. Passing as an Argument in a Method: Sometimes, you might need to pass the current object as an argument to another method. ‘this’ makes this operation simple and efficient, ensuring that the current object is correctly sent to the target method, which can then operate on it as needed.

5. Passing as an Argument in the Constructor Call: Just as with methods, ‘this’ can be used to pass the current object as an argument when calling another constructor within the same class. This is beneficial when constructors have common setup logic that you want to reuse rather than duplicating it in multiple constructors.

6. Returning the Current Class Instance from a Method: In Java, methods can return values, and sometimes you may want to return the current instance of the class from a method. ‘this’ facilitates this operation by representing the current instance, allowing you to return it as the result of a method, which can be particularly useful in methods that configure or modify the object’s state.

Detailed Explanation of Each Usage

1. ‘this’: Referring to the current class instance variable

The ‘this’ keyword can be used to refer to the current class instance variables. This helps resolve ambiguity when a local variable has the same name as an instance variable.

public class Student {

  int id; //instance variable

  Student(int id) {
    this.id = id;
  }

  void display() {
    System.out.println(this.id);  
  }

  public static void main(String[] args) {
    Student s1 = new Student(101);
    s1.display();
  }

}

Output:
101

2. ‘this’: To Invoke Current Class Method

The ‘this’ keyword can also be used to invoke the current class methods.

public class Student {

  void print() {
    display(); 
  }

  void display() {
    System.out.println("Hello");
  }

  public static void main(String[] args) {
    Student s1 = new Student();
    s1.print();
  }

}

Output:
Hello

3. ‘this()’: To Invoke Current Class Constructor

The ‘this()’ syntax invokes the constructor of the current class for constructor chaining.

class Student {

  int id;
  String name;

  Student() {
    System.out.println("Default constructor");
  }

  Student(int id) {
    this();  
    this.id = id;
  }

  Student(int id, String name) {
    this(id);
    this.name = name;
  }

  public static void main(String[] args) {
    Student s1 = new Student(101, "John");
  }

}

Output:
Default constructor

4. ‘this’: To Pass as an Argument in a Method

Passing ‘this’ as a method argument shares the current object reference.

class Student {

  void init(int id, Student s) {
    s.id = id; 
  }

  void print() {
   init(101, this); 
  }

}

5. ‘this’: To Pass as an Argument in Constructor Call

Passing ‘this’ in a constructor shares object references between classes.

class A {

  A() {
    B b = new B(this);
  }

}

class B {

  A a;

  B(A a) {
    this.a = a;
  }

}

6. ‘this’ Keyword for Returning Current Instance

The ‘this’ keyword can return the current class instance.

public class Student {

  int id;

  Student getStudent() {
    return this;
  }

  public static void main(String[] args) {
    Student s1 = new Student();
    Student s2 = s1.getStudent();
    System.out.println(s1 == s2); //true
  }

}

Proving the Reference Identity of ‘this’

Here is a complete program to demonstrate ‘this’ refers to the current object:

public class A {

  int x = 10;

  void m1() {
    System.out.println(this); 
  }

  public static void main(String[] args) {
    
    A a1 = new A();
    
    System.out.println(a1);  
    a1.m1();
    
  }

}

// Output:
A@379619aa
A@379619aa

This proves both ‘this’ and ‘a1’ refer to the same A instance.

Conclusion

To sum it up, the ‘this’ keyword in Java is a crucial tool for keeping code clear and precise in object-oriented programming. Its main usages, from distinguishing between current class instance variables, invoking class methods and constructors, to facilitating smooth interactions through method and constructor calls, make it an indispensable element in Java’s toolbox.

Moreover, ‘this’ can be employed to efficiently return the current class instance from a method, ensuring accessibility and manipulation. By consistently showing its reference identity, ‘this’ maintains its role as a clear and direct connection between objects and their related attributes and methods.

In the world of Java, where object-oriented principles are paramount, ‘this’ empowers developers to create well-organized and efficient applications, fostering clarity and precision in their code.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *