r/learnjava • • 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/

53 Upvotes

13 comments sorted by

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

9

u/Cymry_Cymraeg Jun 02 '20

Beginners need more than just 'concise'. Never be a teacher.

1

u/vqrs Jun 05 '20

Honestly, the article doesn't really seem actually explain things more clearly.

They have some more examples, that's cool though.

The example for accessing the outer class's fields is a case where you don't need it though, so that example seems a bit poorly chosen.

10

u/gaporpaporpjones Jun 02 '20

"Way too elaborate."

With this you get a direct reference to the current object from inside one of its methods.

That's it.

Oh yeah, totally too elaborate.

Everything else is just specific examples of usage, in more depth and in clearer language than Oracle's documentation.

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

u/[deleted] Jun 02 '20

who on earth was confused about "this" ? lol

35

u/ryuzaki49 Jun 02 '20

Javascript developers

8

u/[deleted] Jun 02 '20

0 == [] == true

6

u/ImSuperSerialGuys Jun 02 '20

And evidently, JavaScript creators

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.