Question

I see some codes that have method implementation as

public void setVariables(final int value){
this.value=value;
}

why is the final keyword used in the parameter. why not declare

public void setVariables(int value){
this.value=value;
}

I understand that for classes defined inside methods that access method parameters, they have to declared final

what exactly is the benefit of having final keyword in parameter ?

Était-ce utile?

La solution

Basically, the difference is between

public int doThing( int value )
{
     value = value*2; // OK
     return value;
}

and

public int doThing( final int value )
{
     value = value*2; // Not OK
     return value;
}

This can be helpful to you as a programmer to prevent you from changing the value accidentally.

There is one situation where the final keyword is necessary, and that is if you want to use the value in anonymous nested classes, e.g:

public Object makeThing( final String name )
{
    return new Object()
        {
            @Override
            public String toString(){
                return name; // Won't work if `name` is not `final`.
            }
        };
}

Related:

Autres conseils

to make sure that you don't override that argument

for example to avoid something like this

public void setVariables(final int value){
  value = 1;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top