What difference that final
makes between the code below. Is there any advantage in declaring the arguments as final
.
public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){ return .... } public String changeTimezone(final Timestamp stamp, final Timezone fTz, final Timezone toTz){ return .... }
You can pass final variables as the parameters to methods in Java. A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all.
The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment.
We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class. The main intention of making a method final would be that the content of the method should not be changed by any outsider.
As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.
This saves you from declaring another local final variable in the method body:
void m(final int param) { new Thread(new Runnable() { public void run() { System.err.println(param); } }).start(); }
Extract from The final word on the final keyword
Final Parameters
The following sample declares final parameters:
public void doSomething(final int i, final int j) { // cannot change the value of i or j here... // any change would be visible only inside the method... }
final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style.
Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With