Can someone explain to me in detail the use of 'this'?

后端 未结 9 2012
北海茫月
北海茫月 2021-01-24 21:51

I don\'t really understand the use of \'this\' in Java. If someone could help me clarify I would really appreciate it.

On this website it says: http://docs.oracle.com/ja

9条回答
  •  故里飘歌
    2021-01-24 22:36

    "This" is a hidden "argument" that gets passed for you so that the methods that operate on the object know which object exactly they are to operate on.

    Now imagine you pass the argument of name "x" but the class does have that var name defined already. What happens ? Well, the name x that "belongs" to the object and the argument x are not the same data-object yet they share the name.

    In order to disambiguate, you need to say explicitly "this.x", which tells the compiler that you're talking about the x that already belongs to "this" object. (That is, the current object you're trying to operate on.)

提交回复
热议问题