The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
Answer from Andrew Hare on Stack OverflowUsing the keyword "this" in java - Stack Overflow
What is the meaning of "this" in Java? - Stack Overflow
What is the accepted style for using the `this` keyword in Java? - Software Engineering Stack Exchange
What is the use of the keyword 'this' in Java programming?
can someone help me out on better understanding on when to use the this. keyword ?
I have this code right here:
public class ATM {
public static int totalMoney = 0;
public static int numATMs = 0;
public int money;
public ATM(input money){
this.money = inputMoney;
numATMs += 1;
totalMoney += inputMoney;
}
public void withdrawMoney(int amountToWithdraw){
if (amountToWithdraw <= this.money){
this.money -= amountToWithdraw;
totalMoney -= amountToWithdraw;
}
}
public static void main(String[] args) {
System.out.println
}
}and i understand the majority of this right here. However the part that im not understanding is this part:
public void withdrawMoney(int amountToWithdraw){
if (amountToWithdraw <= this.money){
this.money -= amountToWithdraw;
totalMoney -= amountToWithdraw;
}
}to my understanding, the word this. basically says "we are using THIS variable, in this case money within this method" and the reason that we don't have THIS on amountToWithdraw is basically a global variable that we are accessing ?
sorry for the dumb question. please don't roast me too hard :(
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
this refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like this:
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Then calling frobnicate() on new MyThisTest() will print
1 42 MyThisTest a=42
So effectively you use it for multiple things:
- clarify that you are talking about a field, when there's also something else with the same name as a field
- refer to the current object as a whole
- invoke other constructors of the current class in your constructor
The following is a copy & paste from here, but explains very well all different uses of the this keyword:
Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
private String javaFAQ; void methodName(String javaFAQ) { this.javaFAQ = javaFAQ; }Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the
thisdenotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective ofthisis used or not it denotes the instance variable.thisis used to refer the constructorspublic JavaQuestions(String javapapers) { this(javapapers, true); }This invokes the constructor of the same java class which has two parameters.
thisis used to pass the current java instance as parameterobj.itIsMe(this);Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() { return this; }Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
thiscan be used to get the handle of the current classClass className = this.getClass(); // this methodology is preferable in java
Though this can be done by
Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.
In most IDEs, you can simply mouseover the variable if you want to know. In addition, really, if you're working in an instance method, you should really know all the variables involved. If you have too many, or their names clash, then you need to refactor.
It's really quite redundant.
I prefer to use this. It makes it easier to read code in various editors that color local and instance variables in the same way. It also makes it easier to read the code on a printed page during something like a code review. It's also a fairly strong reminder as to the scope of the variable to other developers.
However, there are arguments against this. In modern IDEs, you can find out the scope of a variable by hovering over it or viewing it in a tree-like structure. You can also change the color and/or font face of variables depending on their scope (even in such a way that, when printed, it's evident what the scope of the variable is).
I believe that ChrisF's last sentence is dead on: be consistent in your usage.
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.
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;
}
}
}