this Keyword

this Keyword

Introduction to this Keyword

  • The this keyword in Java refers to the current instance of the object in a method or constructor.
  • It is used as a reference to an object’s currently executing method or constructor.
  • The this keyword can be used to access instance variables and methods, distinguish between instance variables and local variables, and call one constructor from another within the same class.

Use of this Keyword to Access Instance Variables and Methods

  • Instance variables and methods belong to an instance of a class. The this keyword can be used to directly refer to them.
  • If your method’s parameter names or local variables have the same name as the instance variables, the this keyword can be used to distinguish between them.
  • Example:
      public class Car {
          private String model;
            
          //Method to set the car model
          public void setModel(String model) {
              this.model = model; // 'this' keyword is used to refer to the instance variable
          } 
      }
    

Use of this Keyword for Method Invocation

  • You can invoke one instance method from another within the same class using the this keyword.
  • Typical usage is to call helper methods or chain methods together within the same class.
  • Example:
      public class Car {
          private Integer speed;
            
          //Methods to turn the car on and off
          private void speedUp() {
              this.speed += 10;
          } 
            
          public void accelerate() {
              this.speedUp(); //'this' keyword is used to call the speedUp method within the same class
          } 
      }
    

Use of this Keyword to Call Another Constructor

  • Within a class, you can call one constructor from another using the this keyword.
  • This technique, known as constructor chaining, can avoid duplicating code across constructors.
  • The call to this() must be the first statement in a constructor.
  • Example:
      public class Car {
          private String model;
          private Integer year;
          
          public Car(String model) {
              this.model = model;
          }
          
          public Car(String model, Integer year) {
              this(model); // Using 'this' keyword to call the other constructor
              this.year = year;
          }
      }
    

Important Points on this Keyword

  • The this keyword cannot be used in static methods. This is because static methods don’t operate on instances, so there’s no current instance of the object to refer to.
  • The this keyword can be used to pass an instance of the class to another method.
  • When the this keyword is used as a statement alone, it returns a reference to the current object.