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.