我有一個問題,我們爲什麼要在內部類中使用它時設置字段最終?例如,爲什麼我們應該將textField的修飾符設置爲final? 我的問題是,如果我們不宣稱它是最終的,爲什麼它不可用?爲什麼我們應該將內部類之外的字段的修飾符改爲final?
final TextField textField = new TextField();
Button b = new Button();
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
textField.setText("hello");
}
});
請參閱Jesper對類似問題的回答 - http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in -a-differen –
看到這個。那麼你可以清除... http://stackoverflow.com/questions/3910324/why-inner-classes-require-final-outer-instance-variables-java – subash
如果你需要改變這些值的可能性,你總是可以使用'持有人'。 – msangel