Search code examples
javavariablesfinal

What is the purpose of declaring method parameters final?


So I can fully understand why you may want to make your class final. Imagine String class not being final, and you have a library, in which you have a method that takes a String as an argument and depends on the length() method for some operation, but someone extends the String class and overrides the length to return -1 always..

But I can not figure out why anyone would ever declare a parameter of a method final. Java is pass by value anyway, so if the parameter is a primitive, it is already final (in a sense).. And if you are passing a Reference Type does it guarantee anything to the caller of the method? I do not think so..

void foo(final List<Object> o) {
    o.add(new Object());
} // oops?

So final prevents the following:

void foo(final List<Object> o) {
    o = new ArrayList();
}

But why would I ever want to do this anyway? I can always create a new variable, and it does not assign a new Object to the caller 's variable anyway? (I mean, I can not change what the callers reference refers to anyway, even if the parameter was not declared final..)

My question is, what is the purpose of a final parameter in a method declaration? Is it for the caller? Does it guarantee anything?

I also find strange that the following will compile fine:

public interface MyInterface {
    void foo(final Object o);
}

class MyImpl implements MyInterface {
    @Override
    public void foo(Object o) { // final in interface, not final in impl..
    }
}

but maybe it will make sense once I understand the main question I have.


Solution

  • Sometimes, it helps the fellow programmers or maintenars that they should not change the value of that variable.

    Ex: Imagine a method taking a string parameter. Imagine that it a very long method having 1000 lines of code. If the parameter is not marked as final, the second programmer see an opportunity of changing the value in it. The first programmer resumes the work on the method while not having the knowledge that the variable is assigned a new value. Making it final will fully assure the first programmers intention to be passed on to second.

    Apart from this, if you need to use this variable in any of anonymous class in that method, you can't use it unless it is final.

    Hope this helps.