Method Signature
Hi,
Is it possible to use final in a method signature
to indicate that an object is immutable.
For example:
public Vector2 add(final Vector2 other)
{
return new Vector2(x + other.x, y + other.y);
}
Where the intention is that "other" will not be modified in the method.
thanks
Java doesn't pass by reference anyway, so you wouldn't be able to change the value of the object reference that you want to make final. And you certainly can't prevent methods from being called that change the internals of that object reference. The only way to not change the data in a method is to not change the data in a method ;)
Brian
> No. The final modifier for a variable means that the variable cannot be changed, > i.e. that you cannot assign a new value to it.> It does not mean that the object referred to by the variable cannot be changed.Good point,
The purpose of marking parameters as "final" is to keep the programmer from "accidentally" changing the object the reference points to (hoping that the original reference would point to this new object). As you pointed out, Java is pass-by-value. However, lots of people either don't realize this or they just forget. Marking the parameter as final will make the compiler throw an error if the programmer does something stupid:
public void callMethod(){
Object original = new Object();
doSomething(original);
public void doSomething(final Object o){
o = new Object(); // Doesn't change object that original points to.
}
The compiler (and your IDE) will recognize that you shouldn't be reassigning o to a new object so you just saved yourself a few hours of debugging. I think it's generally considered good practice to declare all parameters as "final," though I've never seen anyone actually do it (NetBeans' refactoring tools do this automatically, though).
Your explanation is likely to confuse people because you say "keep the programmer from "accidentally" changing the object the reference points to".
"Changing the object" is not prevented at all. Changing the reference is. From your explanation, this is what you meant, but that sentence could be misinterpreted.
Fair enough. I probably should have said "The 'final' keyword prevents the programmer from 'accidentally' changing the reference such that it points to a new object." Even that doesn't sound great, though. Maybe I'll just post a URL to this handy article:
http://www.javaranch.com/campfire/StoryPassBy.jsp