What does the final modifier mean on a method parameter?
Use the final modifier on formal parameters to methods when you want to make it clear that the supplied value can be not modified inside the method. The compiler would complain as soon as you accidentally try to assign it a new value inside the method. Anonymous classes that need to access method's parameters are another use case of final method parameters.
- The final keyword on instance and local variables of primitives type only makes primitives behave like constants. You can not reassign value to them.
- The final keyword on a reference variable only restricts the reference itself can not be changed but you still can change the context of the object that the reference points to.
- The final keyword on a formal parameter restricts the formal parameter can not be reassigned inside the method. The final keyword is not part of the method's signature, it can be removed from its overriding method in its subclass.
Only final variables accessible in anonymous class.
interface Worker { void perform_work(); }
Worker getWorker(final int i){
class MyWorker implements Worker
{
public void perform_work()
{
System.out.println(i);
}
};
return new MyWorker();
}
No comments:
Post a Comment