As a user newly switching to Java, I have realized that in our project and some other Java projects, final
keyword is commonly used and after reading several tutorials and SO threads e.g. Excessive use "final" keyword in Java, I think there is some examples that do not require final
keyword. So, here are the points I am confused:
1. Is there any need to use final
keyword in method parameters in classes and interfaces? Because
CompanyDTO findByUuid(final UUID uuid);
//or
@Override
public CompanyDTO findByUuid(final UUID uuid) {
//...
}
2. As far as I know, it also good for thread safety, but I need to understand the basic idea on why it is used almost every possible places in Java. Normally it is used for the variables that will not be changed. So, could you please explain the idea of common usage?
CodePudding user response:
- Is there any need to use final keyword in method parameters in classes and interfaces?
None. Because the effects of using it are miniscule.
- As far as I know, it also good for thread safety
Not at all. A change to a primitive parameter is not visible outside of the method body. On the other hand final
doesn't prevent you from invoking a method on a reference type parameter.
In other words: if your method body does something that ends up causing a race condition between different threads, then final
doesn't help with that at all.
The absolute only thing that using final
for parameters prevents you from doing: re-assigning values to it. So, it can help preventing stupid mistakes. But it almost comes down to pure style. Me for example, I almost never use it, and regard it useless clutter/noise most of the time.
CodePudding user response:
This is usually not necessary unless the object is referenced in more than one place.