Why is Final used in method parameters
When I was coding android I came across the following:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = _inflater.inflate(R.layout.abstract_list_row_item, null);
move.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// if btn is clcked then data is changed an we need to refresh framents
MainAppDataController.getInstance().setIsDataChanged(true);
callWhiteListDB = new CallWhiteListDB(_context);
callWhiteListDB.openToWrite();
callWhiteListDB.insert(allContacts.get(position).name, allContacts.get(position).number);
callWhiteListDB.close();
callBlackListDB = new CallBlackListDB(_context);
callBlackListDB.openToWrite();
callBlackListDB.deleteSingleItem(allContacts.get(position).dbId);
callBlackListDB.close();
populateList(position);
notifyListView(view);
}
});
return convertView;
In the above example, the getView()
method has parameters like int position, View convertView, parent of ViewGroup. My observation was, as soon as I started using the position variable internally onclick()
, Eclipse throws a compilation error and asks for the position as final. Why should I make this final? Final AFAIK is used for constants.
source to share
You are using position
in your anonymous inner class. Therefore, the position is required to be final.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final
or are actually final.
The last modifier indicates that the value of this field cannot be changed.
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
source to share
-
A java variable can be declared using the final keyword. Then the final variable can only be assigned once.
-
A variable that is declared final and not initialized is called an empty final variable. The net final variable forces the constructors to initialize it.
-
Java classes declared final cannot be extended. Limiting inheritance!
-
Final methods cannot be overridden. In particular, it is equal to finite, but in variables it is not.
-
final parameters - parameter values โโcannot be changed after initialization. Do a little java exercise to figure out the implications of final parameters in method overriding.
-
Local Java classes can only refer to local variables and parameters that are declared final.
- The visible advantage of declaring a java variable as static final, the compiled java class provides better performance.
For more information read this
source to share