Reputation: 1
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();
}
});
}
}
Upvotes: 0
Views: 33
Reputation: 3043
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.
Upvotes: 1