Java - final variable requirement in OnClickListener

前端 未结 1 819
傲寒
傲寒 2021-01-21 14:41

I have a program which has a text box that the user can edit. When the user presses a button a Dialog box is created, displaying the user\'s text and a confirm \'yes/no\' option

1条回答
  •  广开言路
    2021-01-21 15:03

    Does the final keyword just ensure the value isn't changed elsewhere, allowing the onClickListener to store the value of IP, knowing it will still be true? is the scope of IP increased?

    In a sense, yes (though this is really the "extent" rather than the "scope": the "scope" is still just the program text between the declaration of IP and the } at the end of the function).

    Implementation-wise, essentially what is happening is that the new DialogInterface.OnClickListener() { ... } has an implicit field named IP that is automatically initialized during the object's construction. The final modifier serves to protect the abstraction of there being a single IP variable, by ensuring that the local variable IP and the implicit field IP continue to refer to the same String instance.

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