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?
Here's one such a tasteful use of final modifier to write an immutable class which represents a point in our 2-dimensional space.
class Point2D {
private final int x;
private final int y;
Point2D(int x, int y) {
this.x = x;
this.y = y;
}
// Remainder omitted for brevity's sake !
}
Once this class instance is created, you can share it freely with other threads and you don't need to bother synchronizing access to it's state. So, immutable objects give you thread safety for free.
You may read JLS § 17.5 for more details on semantics of final fields.