Class members modifier: final

The keyword final is a modifier that can prefix both class fields and methods. If a variable is prefixed with the modifier final, then it is in reality a constant that can't be modified once initialized with a value. This applies to instance, static and local variables, including parameters that are declared final.

  • A final variable of a primitive data type can't change its value once it has been initialized.
  • A final variable of a reference type can't change its reference value once it has been initialized, but the state of the object it denotes can still be changed.


Note: final variable need not be initialized at its declaration, but it must be initialized once before being used.

A final method in a class is complete (i.e., has an implementation) and can't be overridden in any subclass. That is, a subclass can't change its behavior.

So final variables ensure that values can't be changed and final methods ensure that behavior can't be changed.

Note: Variables declared in an interface are implicitly final.


No comments: