Question

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:

  • final: used similar to const parameter in c++. It basically means that value (or in methods - returned value) is not going to change.
  • static: it means that value (or method) is not assigned directly to some object - therefore you are able to use static variable (or method) in other classes without creating object
  • final static: does this combination mean that you have variable (or method), which you are able to access without creating object (static) and you are unable to change its value (like in c++ const) (final)

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???

Was it helpful?

Solution

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.
  • Though you didn't ask about classes, 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.
  • Though 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?"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top