I would like to find out when should you use static, final, static final parameters for variables and (or) methods. As much as I understand:
If I am right, than I don't get one thing. In IntelliJ IDE when you declare method as public final static, it points out that final should be removed, because static has already been pointed out. Why, how, when???
static
means that a field or method belongs to the class, as opposed to individual instances of the class.
final
actually means different things when applied to methods versus fields (or local variables):
final
variables and fields cannot be reassigned. This is fairly similar to C++'s const
.final
methods cannot be overridden, which only applies to methods on instances. When used in this sense, final
is not similar to C++'s const
.Because you cannot override static
methods on classes, the combined modifiers static final
are usually redundant, which is why IntelliJ advises you to remove one of the modifiers.
Additional notes:
final
variables and fields can refer to instances that may change, even though the references themselves cannot change.final
has a third meaning there: final
classes cannot be subclassed. static
can also be applied to nested classes (classes within classes), but it has the same meaning: A static
nested class does not belong to exactly one instance of the enclosing class, which it would otherwise.static
methods cannot be overridden, there's a similar behavior called "shadowing" or "method hiding", by which a subclass offers a static method of the same name and signature as the subclass. This behaves differently from overriding, but similarly, static final
methods cannot be shadowed.Related SO question: "Is it a bad idea to declare a final static method?"