r/learnjava • u/realdiez • Jun 02 '20
When to Use the Java "this" Keyword
I noticed there's more ways to use the "this" keyword than I was aware of, so I wrote this compilation of all the use cases. I also explain what is the purpose of the "this" if you are not that familiar with it. Here's the link to it: https://filipesilva.me/blog/when-to-use-the-java-this-keyword/
8
u/kemotkill90 Jun 02 '20
Use this when you refer to a variable or method from the class.
Example: Private int ciao;
Public void method(int ciao) { This.ciao = ciao; }
This.ciao is the private variable.
-18
Jun 02 '20
who on earth was confused about "this" ? lol
35
4
u/StrangePractice Jun 02 '20
There was one guy in my Java2 class that thought “this” was just a preference thing.
3
u/Nephyst Jun 02 '20
In some cases it can be. If you have an instance variable and you don't have a variable in the current method scope with the same name you can choose to include or omit this.
2
u/pokemaster787 Jun 03 '20
It almost entirely is.
Accessing an object's members or methods doesn't require this unless something with the same name exists in the scope overriding access to the object member.
I.e. in the constructor if your arguments are the same as your member variables, you must use this.
Any other time it is entirely optional. It provides code clarity, but it is almost never necessary.
27
u/desrtfx Jun 02 '20
Way too elaborate.
The best and most concise explanation is from Oracle themselves: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html