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

后端 未结 9 1987
北海茫月
北海茫月 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:23

    this is a reference to the current object, so you access it like any other object - this.x is the x property of this. So x is the argument passed in, which you assign to this.x.

    This is namespacing - the idea that a name for a variable only applies within a given block of code. In java, where you are working within a function belonging to the class, you are inside the namespace for that class, however, if you have another variable with the same name as an argument, it will take precedence, and you instead access the attribute via this.

    this can also be used in other ways. For example, say I want to draw the current object to the screen in a fictional library, from within the class, I could do:

    window.draw(this)
    

    You can also call functions

    this allows us to reference the object we are currently 'inside', so we can pass the current object as an argument. This is very useful. (No pun intended).

提交回复
热议问题