Using “this” with methods (in Java)

前端 未结 7 1961
终归单人心
终归单人心 2020-12-08 16:12

what about using \"this\" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?

The only situation I have encountered is

相关标签:
7条回答
  • 2020-12-08 17:17

    The only reason to prepend this in front of a method invocation is to indicate that you're calling a non-static method. I can't think of any other valid reason to do this (correct me I'm wrong). I don't recommend this convention as it doesn't add much value. If not applied consistently then it could be misleading (as a this-less method invocation could still be a non-static method). How often does one care if the method being invoked is static or not? Furthermore, most IDEs will highlight static methods differently.

    I have heard of conventions where this indicates calling the subclass's method while an absence of this is calling the super class's method. But this is just silly as the convention could be the other way around.

    Edit: As mmyers points out (see comment), this works with static methods. With that, I see absolutely no reason to prepend with this as it doesn't make any difference.

    0 讨论(0)
提交回复
热议问题