What will be the final modifier according to the method / constructor parameters

Hello
What will be the final modifier in the method / constructor parameter?

Example:

class someClass { private final double some; // I understand the use of final in this context, immutability etc.. public someClass(final double some) { // I don't understand what purpose is served by making "some" final this.some = some; } public void someMethod(final double some) { // I don't understand what purpose is served by making "some" final } } 
+4
source share
3 answers

There are two main situations when you need it:

1) you want to use a parameter inside a local class (usually an anonymous class), for example:

 public void foo(final String str) { Printer p = new Printer() { public void print() { System.out.println(str); } }; p.print(); } 

2) you like the style when every variable that is not modified is marked with the word final (usually itโ€™s good practice to keep as many things as possible unchanged).

+5
source

Well, the goal is that you cannot assign a parameter with anything

 public someClass(T some) { some = null; //You can do this. Maybe you want to use the variable `some` later on in your constructor } public someClass(final T some) { some = null; //You can't do this. If you want to reuse `some` you can't. } 

Is it helpful? Little. Normally, argument variables are not used. But in some special situations, you may want to do this.

In any case, if some of them are new someClass(mySome) , mySome will never be changed, although inside the function you assign values โ€‹โ€‹to the argument. There is no such thing as pass-by-refrence in Java. Variables are primitives or references to objects, not to the object itself.

+3
source

From the point of view of the function, some variable is a constant.

Another advantage is to prevent reuse of variables. That is, "some" should be used for only one purpose.

+1
source

All Articles