Thursday, October 28, 2021

this keyword in Java

The “this” keyword refers to the current object in a method or constructor. In Java, this is a reference
variable that refers to the current object.

The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name.

this keyword can also be used:

  1. to refer current class instance variable.
  2. to invoke current class method (implicitly)
  3. to invoke current class constructor.
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this can be used to return the current class instance from the method.

Example:

public class Main {

  int x;

   // Constructor with a parameter

  public Main(int x) {

    this.x = x;

  }

  // Call the constructor

  public static void main(String[] args) {

   Main myObj = new Main(5);

   System.out.println("Value of x = " + myObj.x);

  }

}

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top