Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <code>this</code> 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.</p> <p><strong>Case 1:</strong> Using <code>this</code> 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 <code>x</code> to <code>this.x</code>. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".</p> <pre><code>public class Foo { private String name; public void setName(String name) { this.name = name; } } </code></pre> <p><strong>Case 2:</strong> Using <code>this</code> as an argument passed to another object.</p> <pre><code>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(); } } </code></pre> <p><strong>Case 3:</strong> Using <code>this</code> to call alternate constructors. In the comments, <a href="https://stackoverflow.com/users/239916/trinithis"><strong>trinithis</strong></a> correctly pointed out another common use of <code>this</code>. When you have multiple constructors for a single class, you can use <code>this(arg0, arg1, ...)</code> to call another constructor of your choosing, provided you do so in the first line of your constructor.</p> <pre><code>class Foo { public Foo() { this("Some default value for bar"); //optional other lines } public Foo(String bar) { // Do something with bar } } </code></pre> <p>I have also seen <code>this</code> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload