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

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

    This really has to do with how the java compiler identifies variables by their name. Function (formaal) parameters names precede class member variables. In the first example the formal parameter names are a and b and they do not collide with the member variables x and y so writing

    x = a;
    

    is logical as x can only mean the member variable class Point.

    In the second example x refers both to the formal parameter name and to the member variable. Writing x within the function body refers to the parameter so if you need some other way in order to refer to the member variable x. This is done by explicitly accessing a member via the 'this' keyword.

提交回复
热议问题