Use of ‘this’ in Java

this keyword is a pet name for the current instance within a class. In other word, this is a reference variable that refers to the current object. this does not really affect end code. It is a compile time operator and the code generated with or without it, will remain the same. Where you have to use it, that totally depends on the context.

There could be numerous place where you can use this some of them listed below where you have to use this.

  • Using this to disambiguate variable references.

this keyword should be used to differentiate between local and instance variable.

i.e. in setter methods.

public class Foo {
     private String name;
     public void setName(String name) {
        this.name = name;
    }
}

or in constructors

public class Foo {
    private String name;
    public Foo (String name) {
        this.name = name;
    }
}

 

  • Using this as an argument passed to another object.

public class Foo {
     public String myMethod() {
           Bar bar = new Bar();
           return bar.myMethod(this);
    }

    public String getName() {
          return “Foo”;
    }
}

public class Bar {
      public void myMethod(Foo obj) {
           obj.getName();
     }
}

 

  • Using this to call alternate constructors

class Foo {
      public Foo() {
           this(“Some default value for bar”)
     }

     public Foo(String bar) {
           System.out.println(bar);
     }
}

 

  • Accessing an outer instance from a nested non-static class

public class Outer {
    protected int a;

   public class Inner {
       protected int a;

      public int foo() {
          return Outer.this.a;
     }

     public Outer getOuter(){
        return Outer.this;
     }
  }
}

 

  • this is useful in the builder pattern.

public class User {

     private String firstName;
     private String surname;

    public User(Builder builder){
         firstName = builder.firstName;
         surname = builder.surname;
   }

   public String getName(){
         return firstName + ” ” +  surname;
  }

  public static class Builder {
       public String firstName;
        public String surname;

       public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
      }

     public Builder setSurname(String surname) {
          this.surname = surname;
          return this;
    }

    public User build(){
         return new User(this);
   }

}

   public static void main(String[] args) {
      User.Builder builder = new User.Builder();
      User user = builder.setFirstName(“John”).setSurname(“Doe”).build();
   }

}

 

Hope this had helped you to understand ‘this’ little more.