[java] When should I use "this" in a class?

I know that this refers to a current object. But I do not know when I really need to use it. For example, will be there any difference if I use x instead of this.x in some of the methods? May be x will refer to a variable which is local for the considered method? I mean variable which is seen only in this method.

What about this.method()? Can I use it? Should I use it. If I just use method(), will it not be, by default, applied to the current object?

This question is related to java oop this

The answer is


when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.


"this" is also useful when calling one constructor from another:

public class MyClass {
    public MyClass(String foo) {
        this(foo, null);
    }
    public MyClass(String foo, String bar) {
        ...
    }
}

Unless you have overlapping variable names, its really just for clarity when you're reading the code.


this is a reference to the current object. It is used in the constructor to distinguish between the local and the current class variable which have the same name. e.g.:

public class circle {
    int x;
    circle(int x){
        this.x =x;
        //class variable =local variable 
    }
} 

this can also be use to call one constructor from another constructor. e.g.:

public class circle {
    int x;

    circle() { 
        this(1);
    }

    circle(int x) {
        this.x = x; 
    }
}

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 getFirstName(){
        return firstName;
    }

    public String getSurname(){
        return surname;
    }

    public static class Builder {
        private String firstName;
        private 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();
    }

}

To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.

If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.


this does not affect resulting code - it is compilation time operator and the code generated with or without it will be the same. When you have to use it, depends on context. For example you have to use it, as you said, when you have local variable that shadows class variable and you want refer to class variable and not local one.

edit: by "resulting code will be the same" I mean of course, when some variable in local scope doesn't hide the one belonging to class. Thus

class POJO {
   protected int i;

   public void modify() {
      i = 9;
   }

   public void thisModify() {
      this.i = 9;
   }
}

resulting code of both methods will be the same. The difference will be if some method declares local variable with the same name

  public void m() {
      int i;
      i = 9;  // i refers to variable in method's scope
      this.i = 9; // i refers to class variable
  }

Following are the ways to use ‘this’ keyword in java :

  1. Using this keyword to refer current class instance variables
  2. Using this() to invoke current class constructor
  3. Using this keyword to return the current class instance
  4. Using this keyword as method parameter

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html


Google turned up a page on the Sun site that discusses this a bit.

You're right about the variable; this can indeed be used to differentiate a method variable from a class field.

    private int x;
    public void setX(int x) {
        this.x=x;
    }

However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:

    private int x;
    public void setX(int newX) {
        x=newX;
    }

Same results, but with no chance of a bug where you accidentally refer to x when you really meant to be referring to x instead.

As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.


“This” keyword in java is used to refer current class objects.

There are 6 uses of “this” keyword in java

  1. Accessing class level variable: mostly used if local and class level variable is same
  2. Accessing class methods : this is default behavior and can be ignored
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value : for returning current instance from method
  5. Passing ‘this’ keyword as argument to method Passing : for passing current class instance as argument
  6. this keyword as argument to constructor : for passing current class instance as argument

ref: https://stacktraceguru.com/java/this-keyword-in-java


The second important use of this (beside hiding with a local variable as many answers already say) is when 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;
    }
  }
}

@William Brendel answer provided three different use cases in nice way.

Use case 1:

Offical java documentation page on this provides same use-cases.

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

It covers two examples :

Using this with a Field and Using this with a Constructor

Use case 2:

Other use case which has not been quoted in this post: this can be used to synchronize the current object in a multi-threaded application to guard critical section of data & methods.

synchronized(this){
    // Do some thing. 
}

Use case 3:

Implementation of Builder pattern depends on use of this to return the modified object.

Refer to this post

Keeping builder in separate class (fluent interface)


You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)

Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)


The only need to use the this. qualifier is when another variable within the current scope shares the same name and you want to refer to the instance member (like William describes). Apart from that, there's no difference in behavior between x and this.x.


Will be there any difference if I use "x" instead of "this.x" in some of the methods?

Usually not. But it makes a difference sometimes:

  class A {
     private int i;
     public A(int i) {
        this.i = i; // this.i can be used to disambiguate the i being referred to
     }
  }

If I just use "method()", will it not be, by default, applied to the current object?

Yes. But if needed, this.method() clarifies that the call is made by this object.


With respect to William Brendel's posts and dbconfessions question, regarding case 2. Here is an example:

public class Window {

  private Window parent;

  public Window (Window parent) {
    this.parent = parent;
  }

  public void addSubWindow() {
    Window child = new Window(this);
    list.add(child);
  }

  public void printInfo() {
    if (parent == null) {
      System.out.println("root");
    } else {
      System.out.println("child");
    }
  }

}

I've seen this used, when building parent-child relation's with objects. However, please note that it is simplified for the sake of brevity.


There are a lot of good answers, but there is another very minor reason to put this everywhere. If you have tried opening your source codes from a normal text editor (e.g. notepad etc), using this will make it a whole lot clearer to read.

Imagine this:

public class Hello {
    private String foo;

    // Some 10k lines of codes

    private String getStringFromSomewhere() {
        // ....
    }

    // More codes

    public class World {
        private String bar;

        // Another 10k lines of codes

        public void doSomething() {
            // More codes
            foo = "FOO";
            // More codes
            String s = getStringFromSomewhere();
            // More codes
            bar = s;
        }
    }
}

This is very clear to read with any modern IDE, but this will be a total nightmare to read with a regular text editor.

You will struggle to find out where foo resides, until you use the editor's "find" function. Then you will scream at getStringFromSomewhere() for the same reason. Lastly, after you have forgotten what s is, that bar = s is going to give you the final blow.

Compare it to this:

public void doSomething() {
    // More codes
    Hello.this.foo = "FOO";
    // More codes
    String s = Hello.this.getStringFromSomewhere();
    // More codes
    this.bar = s;
}
  1. You know foo is a variable declared in outer class Hello.
  2. You know getStringFromSomewhere() is a method declared in outer class as well.
  3. You know that bar belongs to World class, and s is a local variable declared in that method.

Of course, whenever you design something, you create rules. So while designing your API or project, if your rules include "if someone opens all these source codes with a notepad, he or she should shoot him/herself in the head," then you are totally fine not to do this.


The this keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.

Case 1: Using this to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x to this.x. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".

public class Foo
{
    private String name;

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

Case 2: Using this as an argument passed to another object.

public class Foo
{
    public String useBarMethod() {
        Bar theBar = new Bar();
        return theBar.barMethod(this);
    }

    public String getName() {
        return "Foo";
    }
}

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

Case 3: Using this to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...) to call another constructor of your choosing, provided you do so in the first line of your constructor.

class Foo
{
    public Foo() {
        this("Some default value for bar");

        //optional other lines
    }

    public Foo(String bar) {
        // Do something with bar
    }
}

I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to oop

How to implement a simple scenario the OO way When to use 'raise NotImplementedError'? PHP: cannot declare class because the name is already in use Python class input argument Call an overridden method from super class in typescript Typescript: How to extend two classes? What's the difference between abstraction and encapsulation? An object reference is required to access a non-static member Java Multiple Inheritance Why not inherit from List<T>?

Examples related to this

this in equals method React: "this" is undefined inside a component function How to access the correct `this` inside a callback? jQuery $(this) keyword Difference between $(this) and event.target? 'this' vs $scope in AngularJS controllers Difference between getContext() , getApplicationContext() , getBaseContext() and "this" Use of "this" keyword in C++ What is context in _.each(list, iterator, [context])? What does 'var that = this;' mean in JavaScript?