In following code, why does local variable which is not declared final work in the ClickListener?? Local variables without final are destroyed at the end of the onCreate
method, so it shouldn't be accessible in the OnClickListener
, right? But, in the following code the value of a
is shown in the Toast. I don't understand why...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String a = "a";
Button btnMinus = findViewById(R.id.btnMinus);
btnMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();
}
});
}
}
Because it is effectively final .
But if you add
String a = "";
a = "a";
and leave the rest of your code unchanged, then it will fail to compile as it wont be effectively final anymore.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.