Reputation: 23
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.
public void setIP(View v){
//get the text inside the editor
EditText et = (EditText) findViewById(R.id.editTextIP);
final String IP = et.getText().toString();
//create dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Set I.P. to : " + IP + " ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
host = IP;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
This code works fine, but my first version would not compile. My IDE complained that I should make the string IP
final
, when It was not.
This got me thinking. What does final
add in this case? What if, for example, I chose to keep a reference to the Dialog, and show it from another method. This means the method above will have returned. So how can the variable IP
linger on?
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?
Upvotes: 2
Views: 886
Reputation: 183361
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 ofIP
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.
Upvotes: 3