将 java 方法参数设置为 final

下面的代码与 final有什么不同。将参数声明为 final有什么好处吗。

public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){
return ....
}


public String changeTimezone(final Timestamp stamp, final Timezone fTz,
final Timezone toTz){
return ....
}
70512 次浏览

It doesn't make a lot of difference. It just means that you can't write:

stamp = null;
fTz = new ...;

but you can still write:

stamp.setXXX(...);
fTz.setXXX(...);

It's mainly a hint to the maintenance programmer that follows you that you aren't going to assign a new value to the parameter somewhere in the middle of your method where it isn't obvious and might therefore cause confusion.

The final prevents you from assigning a new value to the variable, and this can be helpful in catching typos. Stylistically you might like to keep the parameters received unchanged and assign only to local variables, so final would help to enforce that style.

Must admit I rarely remember to use final for parameters, maybe I should.

public int example(final int basicRate){
int discountRate;


discountRate = basicRate - 10;
// ... lots of code here
if ( isGoldCustomer ) {
basicRate--;  // typo, we intended to say discountRate--, final catches this
}
// ... more code here


return discountRate;
}

Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil

BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.

In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.

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();
}

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. It's considered sometimes a good coding practice.

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.

For the body of this method the final keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that using final in general whenever possible will speed things up but that's not the case in recent JVMs.

I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).

It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.

The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example

Suppose we have a method

method1(){

Date dateOfBirth =new Date("1/1/2009");

method2(dateOfBirth);

method3(dateOfBirth); }

public mehod2(Date dateOfBirth) {
....
....
....
}

public mehod2(Date dateOfBirth) {
....
....
....
}

In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.

And this is also one of the Java Coding Best Practices.

- In the past (before Java 8 :-) )

Explit use of "final" keyword affected accessibility of the method variable for internal anonymous classes.

- In modern (Java 8+) lanaguage there is no need for such usage:

Java introduced "effectively final" variables. Local variables and method paramters are assummed final if the code does not imply changing of value of the variable. So if you see such keyword in Java8+ you can assume it is unecessary. Introduction of "effectively final" makes us type less code when using lambdas.

Two advantages that I see are listed :

1 Marking the method argument as final prevents reassignment of the argument inside the method

From you example

    public String changeTimezone(final Timestamp stamp, final Timezone fTz,
final Timezone toTz){
    

// THIS WILL CAUSE COMPILATION ERROR as fTz is marked as final argument


fTz = Calendar.getInstance().getTimeZone();
return ..
    

}

In a complicated method marking the arguments as final will help in accidental interpretation of these arguments as methods local variables and reassigning as compiler will flag these cases as shown in the example.

2 Passing the argument to an anonymous inner class

As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.